外部キーエラーが出た人へ「SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint」


要因

mysqlにてテーブルを外部キーとして連携したときに起こったエラーです。

エラー

php artisan migrateで下記エラー内容

Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `comments` add constraint `comments_ico_id_foreign` foreign key (`ico_id`) references `icos` (`id`) on delete cascade)

解決方法

migrateファイルの生成の順番に問題がありました。

外部キー設定をさせるcomments_tableより後に紐づけたいテーブルであるico_tableがありました。

なので名前を変更してcomments_tableより前に持ってきてphp artisan migrateで治りました。

名前変更前

名前変更後

治ったー!

[vagrant@localhost myblog]$ php artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table (0.02 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table (0.02 seconds)
Migrating: 2019_12_05_215839_create_posts_table
Migrated:  2019_12_05_215839_create_posts_table (0.01 seconds)
Migrating: 2019_12_22_211023_create_icos_table
Migrated:  2019_12_22_211023_create_icos_table (0.02 seconds)
Migrating: 2019_12_23_071756_create_comments_table
Migrated:  2019_12_23_071756_create_comments_table (0.04 seconds)
Migrating: 2020_01_12_020348_tests_migrate_table
Migrated:  2020_01_12_020348_tests_migrate_table (0 seconds)