Foreign Key Laravel 8 foreignId + constrained - 无法添加或更新子行:外键约束失败

Foreign Key Laravel 8 foreignId + constrained - Cannot add or update a child row: a foreign key constraint fails

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

我正在使用新的 foreignId,受 bigint 约束,在 'blogs' table:

中添加一行时出现以下错误

无法添加或更新子行:外键约束失败 (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();
});

我该如何解决?谢谢!

根据documentationconstrained()方法将使用约定来确定table名称:

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