5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Posted at

#要因
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で治りました。

名前変更前
migrate2.jpg

名前変更後
migrate.jpg

治ったー!

[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)

5
2
0

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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?