Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 conditional many to many sync()

I have a content model with many-to-many to categories and tags. Categories and tags are stored in the same table with a boolean tag flag:

category_id | name        | tag
1           | Products    | 0
2           | bestsellers | 1

My Content Model has conditional relationships so defined:

public function categories() {
    return $this->belongsToMany('Foothing\Content\Z\Entities\Category\Eloquent\Category', 'content_content_categories', 'cid', 'tid')->where('tag', false);
}

public function tags() {
    return $this->belongsToMany('Foothing\Content\Z\Entities\Category\Eloquent\Category', 'content_content_categories', 'cid', 'tid')->where('tag', true);
}

While the tag flag is working properly on read operations, i.e.

$categories = Content::find(1)->categories;
$tags= Content::find(1)->tags;

it is not working as expected in sync operations, infact the following code

$content->categories()->sync(1, 2, 3);

will sync the whole table, regardless of the tag flag: tags will be destroyed and my content will be related only to categories 1, 2, 3.

Is it there something bad with this approach?

like image 427
brazorf Avatar asked Nov 08 '22 21:11

brazorf


1 Answers

I've come across the same situation like you, I play the trick like

// the 1st sync will remove all the relationship to the category table
$content->categories()->sync([1, 2, 3]);
// the 2nd sync is to extends the relationship from the 1st
$content->tags()->syncWithoutDetaching([4, 5, 6]);

Both are from same table, that means the id should be different. This should work fine for the problem

like image 69
Js Lim Avatar answered Nov 14 '22 23:11

Js Lim