Reputation: 800
I've got a database structure as follows where item A is in a many to many relationship with B.
This is a true many to many, so:
Item X (object in table A) relates to Y (object in B) multiple times.
Using the laravel attach()
function easily adds these records. However, I need to update and delete these items.
The detach()
and sync()
methods seem to not be appropriate. They assume only one pivot table entry between one record and another record.
If I detach()
then ALL items are deleted. That is not what I want.
So the main point of my question:
If I have the id of the pivot table record, how do I delete/update it... given that detach doesn't work as expected.
Or put another way:
How can I interact with a pivot table object directly?
Upvotes: 3
Views: 1374
Reputation: 800
Thanks to all,
@devk has pointed out a good solution to the problem if you have the child objects available. I've upvoted this answer because it is true and useful for future reference.
Unfortunately, at this particular point I only have the many-to-many id, so i am answering this with a "No - there is no specific way to access the pivot table by id" using the Pivot
or similar objects.
However: to be clear, this can still be done in eloquent using the DB class.
DB::table('many-to-many-lookup')
->where('id', $id)
->take(1)
->delete();
Upvotes: 1
Reputation: 9952
You can use newPivotQuery()
.
Something like that:
Parent::relation()->newPivotQuery()->where('id', $someId)->delete();
The where()
and delete()
statements will apply to the pivot query.
Upvotes: 1