>php artisan -V
Laravel Framework 6.1.0
以下のusersに対して、user_idを外部キー制約として持つsubscribesテーブルを作りました。
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();
});
SQLiteで動作していたマイグレーションだったので、そのままphp artisan migrate
したらエラーになりました。
実行したマイグレーション
Schema::create('subscribes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->unsigned();
$table->string('channel_id');
$table->string('channel_title');
$table->timestamps();
// userが削除されたとき、それに関連するも一気に削除する制約
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
Illuminate\Database\QueryException:
SQLSTATE[HY000]: General error: 1215
Cannot add foreign key constraint
(SQL: alter table `subscribes` add constraint
`subscribes_user_id_foreign` foreign key (`user_id`)
references `users` (`id`) on delete cascade)
PHP - 【Laravel】外部キー制約があるテーブルのmigrateができません|teratail という記事をみて、user_id
カラムを作るときの記述が異なることに気づいてその部分を修正することで、解決しました!
修正点
- $table->integer('user_id')->unsigned();
+ $table->unsignedBigInteger('user_id');
正しいマイグレーション
Schema::create('subscribes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('channel_id');
$table->string('channel_title');
$table->timestamps();
// userが削除されたとき、それに関連するも一気に削除する制約
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
型が違っているからエラーになったっぽいのですが、それじゃあSQLiteはなぜ通った?という疑問が…。