首页 > 解决方案 > Laravel:由于 errno 导致迁移不起作用:150“外键约束格式不正确”错误

问题描述

我正在尝试执行两个单独的表的迁移,包括关系:

第一张表:

public function up()
{

Schema::create('Gerecht', function (Blueprint $table) {
$table->increments('Gerechtcode');
$table->string('Gerecht', 20);

$table->foreign('Gerechtcode')->references('Gerechtcode')->on('Subgerecht');
});

}

第二张表:

public function up()
{

Schema::create('Subgerecht', function (Blueprint $table) {
$table->increments('SubgerechtCode');
$table->string('Gerechtcode',3 );
$table->string('Subgerecht', 25);

$table->foreign('Gerechtcode')->references('Gerechtcode')->on('Gerecht');
});

}

但它给了我一个错误如下:

   Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1005 Can't create table `excellent-taste-db`.`#sql-59c_7d` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `Gerecht` add constraint `gerecht_gerechtcode_foreign` foreign key (`Gerechtcode`) references `Subgerecht` (`Gerechtcode`))

标签: phplaravel

解决方案


在你的第一张桌子上

public function up()
{

Schema::create('Gerecht', function (Blueprint $table) {
$table->increments('Gerechtcode');
$table->string('Gerecht', 20);

$table->foreign('Gerechtcode')->references('Gerechtcode')->on('Subgerecht');
});

}

您正在使用主键 (Gerechtcode) 来引用另一个表。这是不可能的。我认为如果您将第一个表更改为:

public function up()
{

Schema::create('Gerecht', function (Blueprint $table) {
$table->increments('Gerechtcode');
$table->unsignedInteger('SubgerechtCode');
$table->string('Gerecht', 20);

$table->foreign('SubgerechtCode')->references('Gerechtcode')->on('Subgerecht');
});

}

第二个表

public function up()
{

Schema::create('Subgerecht', function (Blueprint $table) {
$table->increments('SubgerechtCode');
$table->string('Subgerecht', 25);
});

}

这样你就有了可以在 Laravel 中处理的一对多关系。但是您的代码不允许我理解您的需求。


推荐阅读