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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With