我已经启动了一个新的Laravel 5.5项目,并且在尝试向我的用户表添加外键时收到以下错误:
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)
这是组织表的迁移代码:
Schema::create('organizations', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('subdomain')->nullable();
$table->timestamps();
$table->softDeletes();
});
这是users表的迁移代码:
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`)