mysql - Laravel 迁移 - 违反完整性约束 : 1452 Cannot add or update a child row: a foreign key constraint fails

标签 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();
});

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

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

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

[Illuminate\Database\QueryException]

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (middleton
.#sql-5d6_162a, CONSTRAINT inventories_local_id_foreign FOREIGN KEY (local_id) REFERENCES contents (id) ON DELETE CASCADE ) (SQL: alter table inventories add constraint inventories_local_id_foreign foreign key (local_id) references contents (id) on delete cascade)

[PDOException]

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (middleton
.#sql-5d6_162a, CONSTRAINT inventories_local_id_foreign FOREIGN KEY (local_id) REFERENCES contents (id) ON DELETE CASCADE )

我做错了什么?

最佳答案

我遇到了同样的问题。通过将 nullable 添加到字段来修复它:

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

请注意,迁移后所有现有行都将具有 some_id = NULL

更新:

从 Laravel 7 开始,有更多更快捷的方式来做同样的事情:

$table->foreignId('some_id')->nullable()->constrained();

nullableconstrained 之前也很重要。

您可以在此处的 official documentation 中找到更多信息

关于mysql - Laravel 迁移 - 违反完整性约束 : 1452 Cannot add or update a child row: a foreign key constraint fails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47266089/

相关文章:

mysql - 当尝试在 Rails 中将数据转换为 json 时,UTF8 崩溃

mysql - AWS DMS 无法连接 Mysql 源数据库,但数据库正在从 mysql 命令连接

php - array_merge_recursive 声明数组不是数组

php - Laravel 5.3 计划不工作(没有计划的命令准备好运行。)

mysql - 无法在 php artisan migrate 上连接到 mysql

mysql - 无法将外键约束添加到数据透视表

mysql - 使用 select 插入时重复记录

Laravel Nova - 前端的输出形式?

javascript - ReactJS - 将参数从 Blade 传递给 JSX

Laravel 迁移 : Add a column with a default value of an existing column