概要
表題の通りですが、外部キー制約を設けたテーブルのmigrateができず、知見をいただければと思います。。
やりたいこと
Users
テーブルのidを参照して、
Posts
テーブルのuser_idとしたいです。
環境
- Laravel5.8
- PHP7
- PostgreSQL10
問題
マイグレーションをかけると、外部参照エラー。
マイグレートの順番などは問題なしです。
エラー文
Migrating: 2019_05_04_084329_create_posts_table Illuminate\Database\QueryException : SQLSTATE[42703]: Undefined column: 7 ERROR: column "user_id" referenced in foreign key constraint does not exist (SQL: alter table "posts" add constraint "posts_user_id_foreign" foreign key ("user_id") references "users" ("id")) at /Path/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664 660| // If an exception occurs when attempting to run a query, we'll format the error 661| // message to include the bindings with SQL, which will make this exception a 662| // lot more helpful to the developer instead of just the database's errors. 663| catch (Exception $e) { > 664| throw new QueryException( 665| $query, $this->prepareBindings($bindings), $e 666| ); 667| } 668| Exception trace: 1 PDOException::("SQLSTATE[42703]: Undefined column: 7 ERROR: column "user_id" referenced in foreign key constraint does not exist") /Path/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458 2 PDOStatement::execute() /Path/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458 Please use the argument -v to see more details.
マイグレーションファイル
- Users
class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
- Posts
class CreatePostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('posts', function (Blueprint $table) { $table->bigIncrements('id'); $table->foreign('user_id')->references('id')->on('users'); // ← これが問題 $table->string('title'); $table->string('message'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('posts'); } }
### まとめ
調べると、型の不一致が原因の可能性が高いといった記事が散見しました。
->unsigned();
をつけるなどしましたが、変化はせず、、、。
すみません、詳しい方がいたらぜひアドバイスいただけると幸いです。

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/05/04 10:11