php - 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`))
解决方案
在你的第一张桌子上:
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 中处理的一对多关系。但是您的代码不允许我理解您的需求。
推荐阅读
- linux - 更改linux目录的所有权
- java - 在 Jenetics 中定义约束
- javascript - 将事件从数据库带到 FullCalendar
- java - 如何通过 Spring Boot App 托管资源中存在的文件
- java - 龙目岛注解@SneakyThrows
- azure - Azure 数据工厂 v2:活动执行管道输出
- imagick - 无法在 imagick mogrify 中同时使用 -profile 和 -format
- angular - Angular Material 中可扩展数据表内的数据表
- json - jq 转换 - json 子数组到分隔字符串
- algorithm - 什么可以是问题的最佳解决方案?