【问题标题】:Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails完整性约束违规:1452 无法添加或更新子行:外键约束失败
【发布时间】:2014-03-12 09:29:00
【问题描述】:

这似乎是一个常见问题,但我找不到与此直接相关的答案。

我有一个用户和设计表,我正在尝试向设计表添加一个外键,以使其引用用户表上的 id。

用户表的迁移:

    Schema::create('users', function(Blueprint $table) {
        $table->increments('id');
        $table->string('username');
        $table->string('email')->unique();
        $table->string('password');
        $table->timestamps();
    });

设计表的迁移:

    Schema::create('designs', function(Blueprint $table)
    {
        $table->engine = 'InnoDB';

        $table->increments('id')->unsigned();
        $table->string('title');
        $table->timestamps();
    });

我正在尝试添加外键的迁移:

public function up()
{
    Schema::table('designs', function(Blueprint $table) {
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
    });
}


/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('designs', function(Blueprint $table) {
        $table->dropColumn('user_id');
    });
}

但我收到错误消息:

[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`bootstrap`.`#sql-512_179`
, CONSTRAINT `designs_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)) (SQL: alter table `designs` add constraint designs_user_
id_foreign foreign key (`user_id`) references `users` (`id`))

我在这里做错了什么?

【问题讨论】:

  • 根据您的 users 迁移,id 列不是无符号的(尽管我不确定 Laravel 中的“增量”是否默认无符号,它确实应该是)所以也许这是你的问题?
  • 我不确定这是真的 - 当我使用增量时,它被设置为无符号(虽然在 laravel 3 中)。

标签: laravel


【解决方案1】:

在 mysql 中,'increments' 是带有 'Unsigned' 属性的 int(10)。 但是,如果您只是添加新列并尝试引用它并获得 SQLSTATE[23000] - 1452 错误消息,请尝试插入有效的引用(键)。或者清空两个表。

【讨论】:

    猜你喜欢
    • 2020-08-13
    • 1970-01-01
    • 2016-10-27
    • 2018-02-12
    • 2021-09-29
    相关资源
    最近更新 更多