eloquent - 无法在 Laravel5.5 上添加外键约束
问题描述
我创建了几个表:
关键需求表:
public function up()
{
Schema::create('keyneeds', function(Blueprint $table)
{
$table->integer('id', true);
$table->integer('segment_id')->index('FK_KN_SEGMENT');
$table->integer('design_id')->index('FK_KEYNEEDS_DESIGN');
$table->integer('admin_id')->index('FK_KN_ADMIN');
$table->string('kntextcolor', 191)->nullable();
$table->string('kntextcolorhover', 191)->nullable();
$table->string('knbgcolor', 191)->nullable();
$table->string('knbgcolorhover', 191)->nullable();
$table->string('knhvize', 191)->nullable();
$table->timestamps();
$table->softDeletes();
$table->engine = 'InnoDB';
});
}
设计表:
public function up()
{
Schema::create('designs', function(Blueprint $table)
{
$table->integer('id', true);
$table->string('design', 191)->nullable();
});
}
我还添加了外键约束
public function up()
{
Schema::table('keyneeds', function(Blueprint $table)
{
$table->foreign('design_id', 'FK_KEYNEEDS_DESIGN')->references('id')->on('designs')->onUpdate('RESTRICT')->onDelete('RESTRICT');
$table->foreign('admin_id', 'FK_KN_ADMIN')->references('id')->on('admins')->onUpdate('RESTRICT')->onDelete('RESTRICT');
$table->foreign('segment_id', 'FK_KN_SEGMENT')->references('id')->on('segments')->onUpdate('RESTRICT')->onDelete('RESTRICT');
});
}
尝试迁移数据库时出现此 SQL 错误:
Can not add external index constraints (SQL: alter table `keyneeds` add constraint` FK_KEYNEEDS_DESIGN` foreign key (`design_id`) references`
igns (
id`) 删除 RESTRICT 更新 RESTRICT)
解决方案
Jonas Staudenmeir 给出了答案:
public function up()
{
Schema::create('designs', function(Blueprint $table)
{
$table->integer('id', true);
$table->string('design', 191)->nullable();
$table->engine = 'InnoDB';
});
}