状況
php aritisan migrateを行うとターミナルでエラーが発生。
General error: 1215 Cannot add foreign key constraint
エラー内容
外部キー制約について、型の不一致が原因らしい。
原因となっているファイルはこれ。
2021_05_01_103119_create_room_players_table
class CreateRoomPlayersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('room_players', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->bigIncrements('id');
$table->interger("room_id")->comment('スコアボードのテーブル');
//この行が問題
//外部キー制約
$table->foreign('room_id')
->references('id')
->on('rooms')
->onDelete('cascade');
//以下省略
参照下のファイルはこれ。
2021_04_20_110007_create_rooms_table
class CreateRoomsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('rooms', function (Blueprint $table) {
$table->bigIncrements('id')->unique
();
$table->string("name")->comment('プレイ名')->unique();
$table->string("password")->comment('スコアボードに入るためのパスワード');
$table->timestamps();
});
}
外部キーの参照元のroomテーブルのidはbigIncrementsなので、bigIncrementsとintegerで一致していない。
またphpMyAdminで確認すると、roomテーブルのidは属性unsignedがついている。
外部キーを設定する場合、データ型が違うとだめらしい。
解決法
データ型を合わせるため、外部キーに指定するroom_idのintegerをbigIntegerに修正する。
(bigIncrementsとbigIntegerで合わせるため)
またroomテーブルのidの属性に合わせて、unsignedもつける。
2021_05_01_103119_create_room_players_table
class CreateRoomPlayersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('room_players', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->bigIncrements('id');
$table->unsignedBigInteger("room_id")->comment('スコアボードのテーブル');
//外部キー制約
$table->foreign('room_id')
->references('id')
->on('rooms')
->onDelete('cascade');
$table->integer("user_id")
php artisan migrate:rollback
php artisan migrate:fresh を実行し、
php artisan migrate を実行すると、無事migrationできた。