You should use unsignedBigInteger For all the foreign keys if id is bigIncrements @hjortur17
May 5, 2019
4
Level 14
Can not add a foreign key
Hi, i'm trying to add a foreign key in my table but I always get this error message:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `thread_subscriptions` add constraint `thread_subscriptions_thread_id_foreign` foreign key (`thread_id`) references `threads` (`id`) on delete cascade)
at /Users/hjorturfreyrlarusson/websites/project/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
660| // If an exception occurs when attempting to run a query, we'll format the error
661| // message to include the bindings with SQL, which will make this exception a
662| // lot more helpful to the developer instead of just the database's errors.
663| catch (Exception $e) {
> 664| throw new QueryException(
665| $query, $this->prepareBindings($bindings), $e
666| );
667| }
668|
Exception trace:
1 PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")
/Users/hjorturfreyrlarusson/websites/project/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458
2 PDOStatement::execute()
/Users/hjorturfreyrlarusson/websites/project/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458
Please use the argument -v to see more details.
Here is my migration:
Schema::create('thread_subscriptions', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->bigIncrements('id');
$table->unsignedInteger('user_id');
$table->unsignedInteger('thread_id');
$table->timestamps();
});
Schema::table('thread_subscriptions', function($table) {
$table->foreign('thread_id')
->references('id')
->on('threads')
->onDelete('cascade');
});
Level 24
2 likes
Please or to participate in this conversation.