cloude
cloude

Reputation: 346

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

I have 'categories_blogs' and 'blogs' migration.

I'm using new foreignId, constrained with bigint, I get this follow error when add a row in 'blogs' table:

Cannot add or update a child row: a foreign key constraint fails (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();
  });
   

Instead without bigint and old foreign key way, works fine:

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

How can I fix it? thanks!

Upvotes: 2

Views: 1579

Answers (1)

STA
STA

Reputation: 34678

According to the documentation, constrained() method will use conventions to determine the table name :

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

Upvotes: 2

Related Questions