Home > Software design >  Laravel 9 Foreign Key Constraints issue on INSERT
Laravel 9 Foreign Key Constraints issue on INSERT

Time:02-17

I tried following what the documentation says here regarding foreign keys:

1

users:

2

role_user:

3

I am having some issues in my role_user this is the error:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`usersexam`.`role_user`, CONSTRAINT `role_user_role_id_foreign` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE)

this is it's migration: (tried to follow the laravel docs syntax)

public function up()
{
    Schema::create('role_user', function (Blueprint $table) {
        $table->foreignId('user_id')->constrained()->cascadeOnDelete();
        $table->foreignId('role_id')->constrained()->cascadeOnDelete();
    });
}

then here is my insert query:

4

What did I do wrong in the process? any help would be appreciated.

CodePudding user response:

You have to insert data into the roles and users table before inserting anything into the role_user table

CodePudding user response:

You are trying to add an id in the pivot table that does not exist in the parent table. Make sure the value that you are inserting into the foreign keys exists in the parent table(s).

You're getting this error because you're trying to insert a row to the role_user table that does not have a valid value for the role_id field based on the values currently stored in roles table.

So what you need to do is insert data into both roles and users tables first.

  • Related