【问题标题】:Foreign Key Laravel 8 foreignId + constrained - Cannot add or update a child row: a foreign key constraint fails外键 Laravel 8 foreignId + 约束 - 无法添加或更新子行:外键约束失败
【发布时间】:2021-09-21 01:53:27
【问题描述】:

我有 'categories_blogs' 和 'blogs' 迁移。

我正在使用新的 foreignId,受 bigint 约束,在“博客”表中添加一行时出现以下错误:

无法添加或更新子行:外键约束失败(test.blogs, CONSTRAINT blogs_category_id_foreign FOREIGN KEY (category_id) REFERENCES categories_blog (id))

    Schema::dropIfExists('categories_blogs');

    Schema::create('categories_blogs', function (Blueprint $table) {
        $table->id();
        $table->string('category_name');
        $table->timestamps();
    });

   Schema::create('blogs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('category_id')->constrained('categories_blog');
            $table->string('slug');
            $table->string('title');
            $table->timestamps();
  });
   

没有 bigint 和旧外键方式,工作正常:

Schema::dropIfExists('categories_blogs');

Schema::create('categories_blogs', function (Blueprint $table) {
    $table->increments('id');
    $table->string('category_name');
    $table->timestamps();
});

Schema::create('blogs', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('category_id')->unsigned();
    $table->foreign('category_id')->references('id')->on('blogs')->onDelete('cascade');
    $table->string('slug');
    $table->string('title');
    $table->string('description');
    $table->longtext('content');
    $table->timestamps();
});

我该如何解决?谢谢!

【问题讨论】:

    标签: mysql laravel migration


    【解决方案1】:

    根据documentationconstrained()方法会使用约定来确定表名:

    $table->foreignId('category_id')->constrained('categories_blogs');
    

    【讨论】:

    • 你是对的!这就是问题所在,令人难以置信的疏忽。谢谢!
    • 不要忘记将答案标记为已接受✅
    • 是的,我完成了,但你删除了它。问题只是因为我使用了 constrained('categories_blog') 而不是 constrained('categories_blogs')。
    猜你喜欢
    • 2017-09-14
    • 2015-07-26
    • 2020-07-29
    • 1970-01-01
    • 2020-10-04
    相关资源
    最近更新 更多