I'm trying to update additional columns on a pivot table using Laravel 5.
I have a model Person and Artist. There's a many-to-many-relation between them. The pivot table here contains an additional column named active, which i'm trying to update.
On my view I want to present a select2 for current-members and another select2 for past-members. These should all arrive in the same pivot table, but the active field determines whether or not the person is still in the band.
Here's what I have:
Artist-model (declaring the additional column):
class Artist extends Model {
public function members() {
return $this->belongsToMany('App\Entities\Person')->withPivot('active');
}
}
Person-model (I don't need the function, but defined it anyway)
class Person extends Model {
public function artist() {
return $this->belongsToMany('App\Entities\Artist')->withPivot('active');
}
}
Storing the two member-lists ($artistData is the filtered form-input):
$artist->members()->attach($artistData->members, array('active' => TRUE));
$artist->members()->attach($artistData->past_members, array('active' => FALSE));
This works like a charm.
But next, I need to update the relations.
- A person can be added (create new pivot)
- A person can be moved to the other select2 (update "active"-field)
- A person can be removed (I don't use softDeletes so delete the pivot)
I tried following code, but it's not working as I expected (I really want to use something like this):
// One would expect this to work (sync m2m, for members set active=TRUE, for past_members set active=FALSE)
// first detach existing pivots which are not in the members-list, and attach (if necessary) the remaining members. set all "actives" to TRUE
$artist->members()->sync($artistData->members, array('active' => TRUE));
// keep the above set pivots, and attach (if necessary) the past_members, setting all "actives" to FALSE
$artist->members()->syncWithoutDetaching($artistData->past_members, array('active' => FALSE));
I searched stackoverflow and saw something like this:
// This on the other hand works, but you'd have to add multiple conditions to make it work without getting bugs
// Which would be extremely annoying
$merged_members = array_merge($artistData->members, $artistData->past_members);
$actives = array_merge(
array_fill(0, count($artistData->members), ['active' => true]),
array_fill(0, count($artistData->past_members), ['active' => false])
);
$syncData = array_combine($merged_members,$actives);
$artist->members()->sync($syncData);
What's the best way to handle this?
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2Bc5iPS
via IFTTT
Aucun commentaire:
Enregistrer un commentaire