gravitymedianet's avatar

$model->morphRelationship->where()->sync();

I have the classic tags & taggables tables in my app. Any model can be made "taggable", in which case we can apply the tags to the model using the taggables pivot table. The only issue is that I have a category column on my tags table, as not all tags apply to each model. This is so that I don't have to have a separate table for each group of tags.

My relationship(s) looks like this (where model = $supplier):

public function industries()
{
		return $this->morphToMany(Tag::class, 'taggable')->where('tags.category', "industry");
}

public function paymentMethods()
{
		return $this->morphToMany(Tag::class, 'taggable')->where('tags.category', "payment_method");
}

When I call $supplier->industries or $supplier->paymentMethods, I get only the tags with tag.category => 'industry' or tag.category => 'payment_method', as expected.

The issue is when I use the attach/detach/sync methods, e.g.:

$supplier->industryTags()->sync($myTagData);

What happens is ALL the tags associated with that model are deleted/synced, not just the "industry" ones, but the payment_method tags as well.

Is there a way to sync with a where condition that will only delete the tags within that same category?

0 likes
0 replies

Please or to participate in this conversation.