LoginSignup
0
2

More than 3 years have passed since last update.

Laravel SQLiteからMySQLに変更したら外部キー制約のマイグレーションが失敗してハマった

Posted at
>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はなぜ通った?という疑問が…。

0
2
1

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
2