使用 Laravel 迁移添加外键约束

Adding a foreign key constraint with a Laravel Migration

我已经启动了一个新的 Laravel 5.5 项目,但在尝试向我的 users 添加外键时收到以下错误 table:

General error: 1215 Cannot add foreign key constraint (SQL: alter table users add constraint users_organization_id_foreign foreign key (organization_id) references organizations (id) on delete cascade)

这是 organization table 的迁移代码:

Schema::create('organizations', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('subdomain')->nullable();
    $table->timestamps();
    $table->softDeletes();
});

这是 users table 的迁移代码:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('organization_id')->unsigned();
    $table->foreign('organization_id')->references('id')->on('organizations');
    $table->string('first_name');
    $table->string('last_name');
    $table->string('email')->unique();
    $table->timestamps();
    $table->softDeletes();
});

我已经在线研究了这个错误,通常要确保数据类型相同。据我所见,它们是相同的。更疯狂的是,如果我直接在数据库中 运行 这个查询,它就可以工作:

alter table `users` add constraint `users_organization_id_foreign` foreign key (`organization_id`) references `organizations` (`id`)

默认情况下,在每个 Laravel 全新安装中 users 首先创建 table。但是由于您要在此 table 中添加约束,因此您需要先创建 organizations table。

因此,通过更改文件名中的 organizations 迁移日期,将 organizations table 迁移放在 users table 迁移之前:

2014_01_01_000000_create_organizations_table.php

同意 Alexey 的回答。我还建议您在 运行 迁移之前 enable/disable 外键约束:

Schema::disableForeignKeyConstraints();
// Your migration code.
Schema::enableForeignKeyConstraints();

这样您就不需要重命名迁移文件了。