Php 通过Laravel迁移添加外键约束
我已经启动了一个新的Laravel 5.5项目,在尝试将外键添加到我的Php 通过Laravel迁移添加外键约束,php,mysql,laravel,laravel-5,database-migration,Php,Mysql,Laravel,Laravel 5,Database Migration,我已经启动了一个新的Laravel 5.5项目,在尝试将外键添加到我的users表时,我收到以下错误: Schema::create('organizations', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('subdomain')->nullable(); $table->timest
users
表时,我收到以下错误:
Schema::create('organizations', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('subdomain')->nullable();
$table->timestamps();
$table->softDeletes();
});
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();
});
一般错误:1215无法添加外键约束(SQL:alter tableusers
add constraintusers\U organization\U id\U foreign
外键(organization\U id
)引用组织(id
)在删除级联中)
以下是组织
表的迁移代码:
Schema::create('organizations', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('subdomain')->nullable();
$table->timestamps();
$table->softDeletes();
});
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();
});
以下是用户
表的迁移代码:
Schema::create('organizations', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('subdomain')->nullable();
$table->timestamps();
$table->softDeletes();
});
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 fresh安装中,首先创建用户
表。但由于要在此表中添加约束,所以需要首先创建组织
表
因此,通过更改文件名中的组织
迁移日期,将组织
表迁移放在用户
表迁移之前:
2014_01_01_000000_create_organizations_table.php
同意亚历克赛的回答。我还建议您在运行迁移之前启用/禁用外键约束:
Schema::disableForeignKeyConstraints();
// Your migration code.
Schema::enableForeignKeyConstraints();
这样,您就不需要重命名迁移文件。您是否已将dbal添加到composer.json中?如果未添加,composer需要/dbal