Reputation: 21493
I have a pivot table set up as follows:
user_roles
user_id //fk->users.id
assoc_id //nullable fk->association.id
role //varchar
I set my database up this way because roles represent a many to many relationship: an association has many users, and a user may be in many associations. every user has a role within an association.
However, there are some roles that exist that can exist outside of an association. The database is configured to accept a null value in the assoc_id
field and I can manually insert one from the command line, but when I attempt to execute
$user->roles()->attach(NULL, "outside contractor");
in my seed file, I get an error saying
[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update
a child row: a foreign key constraint fails (`database`.`user_roles`, CONSTR
AINT `user_roles_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users
` (`id`)) (SQL: insert into `user_roles` () values ())
this is particularly confusing because shouldn't the first argument here be referring to the assoc_id
? When I replace the NULL
with a valid assoc_id
,
$user->roles()->attach(1, "outside contractor");
the insert works fine, and the first argument refers to the assoc_id
in the table.
What is going wrong?
Upvotes: 2
Views: 1968
Reputation: 81187
If you don't provie a key/keys for attach
/sync
, Eloquent will not insert anything. It's rather expected behaviour, since what you are trying to do is:
Create a link between X and null
this is not what ORM is supposed to do.
Instead insert those rows manually:
$data = [
'user_id' => 99,
'assoc_id' => null,
'role' => 'outside contractor'
];
DB::table('user_roles')->insert($data);
Upvotes: 3