Wednesday, October 4, 2017

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `` add constraint `_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `profiles` add constraint `profiles_user_id_foreign` foreign
 key (`user_id`) references `users` (`id`) on delete cascade).


Ok , this Error on laravel migration for a new table, when trying to add a foreigen key to profile table references User id  in users table,  what will solve this issue is to change the user_id type to match the data type of (id) in users table :

$table->integer('user_id')
to
$table->integer('user_id')->unsigned()->nullable();

Also, this error can happen, if the referenced table is not created yet. So, if the users table in this example is not exist in the database. then the same error (1215) will be triggered .

No comments:

Post a Comment