Laravel migration - 完整性约束违规:1452无法添加或更新子行:外键约束失败

Lef*_*eff 9 mysql laravel laravel-migrations

我正在尝试为inventories使用此迁移创建的表运行迁移:

Schema::create('inventories', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('remote_id')->unsigned();
    $table->integer('local_id')->unsigned();
    $table->string('local_type');
    $table->string('url')->nullable()->unique();
    $table->timestamps();
});
Run Code Online (Sandbox Code Playgroud)

我正在尝试添加运行迁移,我在表中添加了一个外键:

Schema::table('inventories', function (Blueprint $table) {
    $table->foreign('local_id')->references('id')->on('contents')->onDelete('cascade');
});
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试运行迁移时出现错误:

[Illuminate\Database\QueryException]
SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败(middleton
.#sql-5d6_162a,CONSTRAINT inventories_local_id_foreignFOREIGN KEY(local_id)REFERENCES contents(id)ON DELETE CASCADE)(SQL:alter table 在删除级联上inventories添加约束 inventories_local_id_foreign外键(local_id)引用 contents(id))

Schema::create('inventories', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('remote_id')->unsigned();
    $table->integer('local_id')->unsigned();
    $table->string('local_type');
    $table->string('url')->nullable()->unique();
    $table->timestamps();
});
Run Code Online (Sandbox Code Playgroud)

SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败(middleton
.#sql-5d6_162a,CONSTRAINT inventories_local_id_foreignFOREIGN KEY(local_id)REFERENCES contents(id)ON DELETE CASCADE)

我究竟做错了什么?

Rom*_*rik 11

有同样的问题.通过添加nullable到字段来修复它

Schema::create('table_name', function (Blueprint $table) {
    ...
    $table->integer('some_id')->unsigned()->nullable();
    $table->foreign('some_id')->references('id')->on('other_table');
    ...
});
Run Code Online (Sandbox Code Playgroud)

请注意,迁移后所有已存在的行都将具有some_id = NULL


Dar*_*hta 8

您可能在inventories表中有一些记录,表local_id中没有对应id的记录contents,因此出错.您可以通过以下两种方式之一解决它:

  • foreign_key_checks关闭后运行迁移.这将禁用现有行的外键约束(如果这是您想要的).它在这里记录
  • 仅插入表中具有相应id字段的记录contents.您可以使用INSERT INTO.. WHERE EXISTS查询过滤掉记录,并仅插入这些记录.