-
Hi, I started using tags for products with many to many relationships. I have a tag table and a product_tag table as pivot. I'm splitting different tags by type like occasion, recipients and maybe more. It is working fine, if I just save one type of tags. If I save both, only the first relation is getting saved. The 2nd is getting ignored. If I swap the sync order it's saving the other relation. I have no idea what might be wrong. $product->fill($request->get('product'));
$product->save();
$product->recipients()->sync(optional($request->get('product'))['recipients']);
$product->occasions()->sync(optional($request->get('product'))['occasions']); Product.php /**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function occasions()
{
return $this->belongsToMany(Occasion::class, 'product_tag', 'product_id', 'tag_id')->where('type', Occasion::TYPE);
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function recipients()
{
return $this->belongsToMany(Recipient::class, 'product_tag', 'product_id', 'tag_id')->where('type', Recipient::TYPE);
} Occaion.php /**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function products()
{
return $this->belongsToMany(Product::class, 'product_tag', 'tag_id', 'product_id');
} And I'm using the scope method to apply the type filter. /**
* @param Builder $query
*
* @return Builder
*/
public function scopeType(Builder $query): Builder
{
return $query->where('type', self::TYPE);
} Screen Relation::make('product.occasions.')
->fromModel(Occasion::class, 'name', 'id')
->multiple()
->applyScope('type')
->title(__('Occasions')),
Relation::make('product.recipients.')
->fromModel(Recipient::class, 'name', 'id')
->multiple()
->applyScope('type')
->title(__('Recipients')), Another problem is, that the relation is always removing and adding the pivot entires when I save. Doesn't matter if there was no change at all. So the increment ids are increasing with every product save. If I do a check for changed values and skip the sync if there was no change, it will delete the pivot entries. I also tested int casting to make sure the ids are the same for the system. I guess thats a pure laravel thing I have to check. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Just got an idea while debugging the code. It was always handling the IDs for both tag types on each sync. I added a generic Tag model and merge the IDs and sync that all together. Might not be the best way but works fine so far. |
Beta Was this translation helpful? Give feedback.
Just got an idea while debugging the code. It was always handling the IDs for both tag types on each sync. I added a generic Tag model and merge the IDs and sync that all together. Might not be the best way but works fine so far.