Laravel迁移:无法添加外键约束

时间:2018-10-19 17:39:07

标签: php database laravel foreign-keys laravel-migrations

我试图通过Laravel Migrations将外键约束添加到我的数据库表中,但是我总是收到这样的错误:

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

tasks表的迁移看起来像这样:

<?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');
    }
}

这是task_lists表:

<?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');
    }
}

我无法解决问题,将非常感谢您提供任何帮助。

提前谢谢!

2 个答案:

答案 0 :(得分:0)

您必须检查迁移顺序。显然,您必须先执行de Users表迁移,然后再执行Tasks表迁移。如果问题仍然存在,请尝试在up()方法内部以及(Schemma :: create)之后进行如下操作:

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

答案 1 :(得分:0)

检查您的表是否使用InnoDB引擎,以及您引用的列是否具有相同的数据类型,即它们都是无符号的int / string / etc。

您可能希望将MySQL服务器默认引擎更改为InnoDB(有时默认为MyISAM)。 Laravel也可以使用/config/database.php(mysql.engine)

中的设置自动进行设置。

https://dba.stackexchange.com/questions/1/what-are-the-main-differences-between-innodb-and-myisam