Santiago Ramirez
Santiago Ramirez

Reputation: 317

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row on laravel migration

I'm addign a foreign key to my appointments table, my DB is called arl through laravel migrations

but when I run migration:

    public function up()
{
    Schema::table('appointments', function (Blueprint $table) {

        $table->foreign('order_detail_id')->references('id')->on('order_details');
        
    });
}

I got this error:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`arl`.`#sql-5470_6`, CONSTRAINT `appointments_order_detail_id_foreign` FOREIGN KEY (`order_detail_id`) REFERENCES `order_details` (`id`)) (SQL: alter table `appointments` add constraint `appointments_order_detail_id_foreign` foreign key (`order_detail_id`) references `order_details` (`id`))

checking the error I don't know why the sql doesn't recognize my table name and put this weird name arl`.`#sql-5470_6 should be arl`.`appointments

I went to heidi sql to replicate de query and I got the same error.

Edit: the problem it's on laragon local serve I tried with xampp and worked fine

Upvotes: 0

Views: 761

Answers (2)

Abdullah Ibrahem
Abdullah Ibrahem

Reputation: 11

You must delete all rows in table order_details and try again.

Or:

add ->default( any id from table order_details)
$table->unsignedBigInteger('order_detail_id')->default(1);
$table->foreign('order_detail_id')->references('id')->on('order_details');

Upvotes: 1

Ahmed Ali
Ahmed Ali

Reputation: 133

try this :

    $table->unsignedBigInteger('order_detail_id');
    $table->foreign('order_detail_id')->references('id')->on('order_details');

Upvotes: 0

Related Questions