sync pivot-table with additional columns

Posted 1 year ago by pdc

I'm trying to update additional columns on a pivot-table. I have a model "Person" and "Artist". There's a many-to-many relationship between them. The pivot-table contains a column named "active". This is the one i'm trying to set, and determines whether or not a person is still in the band.

class Artist extends Model {    
    public function members() {
        return $this->belongsToMany('App\Entities\Person')->withPivot('active');
class Person extends Model {
    public function artist() {
        return $this->belongsToMany('App\Entities\Artist')->withPivot('active');

Storing the members and quit_members works like a charm

$artist->members()->attach($artistData->members, array('active' => TRUE));
$artist->members()->attach($artistData->past_members, array('active' => FALSE));

To update the members I'd expected below code to work:

// 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));

But somehow this code still detaches the existing entities. How can I deal with this. I don't want to add another pivot-table for this so that's why i use the active-column.

GitHub reference (line 45) https://github.com/PieterjanDeClippel/LyricDB/blob/master/app/Services/ArtistService.php

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.