0
0

Unknown column 'posts.users_id' in 'where clause'が出た時の対処

Last updated at Posted at 2023-11-08

環境

% php artisan -V
Laravel Framework 10.30.1
% php -v
PHP 8.2.10 (cli) (built: Aug 31 2023 18:52:27) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.2.10, Copyright (c) Zend Technologies
    with Zend OPcache v8.2.10, Copyright (c), by Zend Technologies

User

Users.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

# Classは処理のまとまりのこと、Modelはその処理の内容
class Users extends Model
{
    use HasFactory;

    public function Posts()
    {
# PostsというクラスがあることはPosts.phpに定義済み
        return $this->hasMany(Posts::class);
    }
}
2023_11_04_225616_create_users_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('users');
    }
};

Post

Posts.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

# Classは処理のまとまりのこと、Modelはその処理の内容
class Posts extends Model
{
    use HasFactory;

    public function Users()
    {
        return $this->belongsTo(Users::class);
    }
}
2023_11_04_225632_create_posts_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')
            ->references('id')
            ->on('users');
            $table->text('title');
            $table->text('subject');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};

このようにファイルを作成し、"php artisan tinker"を実行。
users_idがuserのidとリレーションが出来ているのかを確認するとエラーが出てきた。

> $user = Users::find(18);
[!] Aliasing 'Users' to 'App\Models\Users' for this Tinker session.
= App\Models\Users {#6628
    id: 18,
    name: "斉藤 舞",
    email: "youichi.sasada@example.net",
    email_verified_at: null,
    password: "$2y$12$lDrHtpTiiB2rDtk7AnAWlesip3BVi.mg.2L4FK/jDjIJz2EHyAM76",
    remember_token: null,
    created_at: "2023-11-05 00:14:34",
    updated_at: "2023-11-05 00:14:34",
  }

> $user->Posts;

   Illuminate\Database\QueryException  SQLSTATE[42S22]: Column not found: 1054 Unknown column 'posts.users_id' in 'where clause' (Connection: mysql, SQL: select * from `posts` where `posts`.`users_id` = 18 and `posts`.`users_id` is not null).

下記のように修正するとリレーションを確認することが出来た。

Users.php
class Users extends Model
{
    use HasFactory;

    public function Posts()
    {
# PostsというクラスがあることはPosts.phpに定義済み
        return $this->hasMany(Posts::class, 'user_id');#", 'user_id'"を追加
    }
}
> $user->Posts;
= Illuminate\Database\Eloquent\Collection {#7248
    all: [
      App\Models\Posts {#6292
        id: 21,
        user_id: 20,
        title: "Hello",
        subject: "Occaecati quia quia ea explicabo similique voluptatem. Suscipit cumque repudiandae quia voluptas adipisci inventore doloribus. Aut cumque qui sed odit.",
        created_at: "2023-11-08 20:24:33",
        updated_at: "2023-11-08 20:24:33",
      },
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0