Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Attach/Detach model from pivot depending on pivot extra field

I have a Many To Many relationship between Council and ManagementUnit. The associated entities change from year to year, so the pivot table is like this:

council_id
management_unit_id
year

My problem is that the same combined council_id + management_unit_id keys can appear several times, so I don't know how to attach() or detach() the models. For example, if I had this:

council_id | management_unit_id | year
1          | 1                  | 2010
1          | 1                  | 2011
1          | 1                  | 2012

how would I detach Council(1) from ManagementUnit(1) only for 2011? or how would I attach a Council(1) to ManagementUnit(1) for 2013?

Working with Laravel 5.1

like image 993
Cmorales Avatar asked Oct 23 '15 17:10

Cmorales


2 Answers

Not sure how your relations are set so you might have to adjust this a little. but give it a try:

$managementUnit = ManagementUnit::find(1);
$managementUnit->councils()->where('id', 1)->wherePivot('year', 2011)->detach(1);
like image 164
Pawel Bieszczad Avatar answered Sep 26 '22 07:09

Pawel Bieszczad


In laravel 5.6 only worked with:

$managementUnit = ManagementUnit::find(1);
$managementUnit->councils()->where('conuncils.id', 1)->wherePivot('year', 2011)->detach();
like image 39
LipeTuga Avatar answered Sep 25 '22 07:09

LipeTuga