简体   繁体   中英

Laravel Migrations: Cannot add foreign key constraint

I am trying to add foreign key constraints to my database tables via Laravel Migrations, but I always get an error like this:

Illuminate\Database\QueryException  :
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
(SQL: alter table `tasks` add constraint `tasks_task_list_id_foreign` foreign key (`task_list_id`) references `task_lists` (`id`))

The migration for the tasks table looks like this:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTasksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->index();
            $table->integer('task_list_id')->unsigned()->index();
            $table->string('task');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('task_list_id')->references('id')->on('task_lists');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tasks');
    }
}

And that's the task_lists table:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTaskListsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('task_lists', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->index();
            $table->string('name');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('task_lists');
    }
}

I can't figure out the problem and would highly appreciate any kind of help.

Thank you in advance!

You have to check the order of your migrations. Obviously, you have to run de Users table migration before the Tasks table migration. If the problem persist, try to make something like this inside the up() method and after the (Schemma::create):

    Schema::table('task_lists', function($table){
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM