【问题标题】:Laravel Migrations: Cannot add foreign key constraintLaravel 迁移:无法添加外键约束
【发布时间】:2019-03-24 15:30:23
【问题描述】:

我正在尝试通过 Laravel 迁移向我的数据库表添加外键约束,但我总是收到如下错误:

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

我无法找出问题所在,非常感谢任何形式的帮助。

提前谢谢你!

【问题讨论】:

  • 您是先创建task_lists 表吗?两个表都使用InnoDB 引擎吗?
  • 两者都使用InnoDBtask_lists 表是在tasks 表之后创建的。
  • 你必须创建task_lists 之前 tasks
  • 是的,我想这就是问题所在。说得通。但是如何更改订单?
  • 您必须更改文件名中的日期。

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


【解决方案1】:

您必须检查迁移的顺序。显然,您必须在 Tasks 表迁移之前运行 de Users 表迁移。如果问题仍然存在,请尝试在 up() 方法内和 (Schemma::create) 之后进行类似操作:

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

【讨论】:

    猜你喜欢
    • 2017-03-27
    • 2021-08-30
    • 2020-09-21
    • 2020-03-12
    • 2020-01-20
    • 2019-07-31
    • 2014-05-02
    相关资源
    最近更新 更多