I implemented 3 table :product , shop and product_shop for pivot.
in the pivot table I have 4 column: id , product_id , shop_id , product_count.
and I made an observer for ProductShop model , but the deleted method not fired !
should I create detached method for pivot observer ?
thanks
CodePudding user response:
pivot table don't need to model.
to add pivot use attach, when creating a product and i'm need to add to a shop just use attach like: $product->my_relation_to_pivot()->attach(id of shop or array of ids shops);
for update use sync, like: $product->my_relation_to_pivot()->sync(id of shop or array of ids shops)
note: this method will delete all ids in database where not in array or int value you passed to him.
for delete use detach, like: $product->my_relation_to_pivot()->detach() will delete all records with product_id equal $product->id
CodePudding user response:
I created a foreach on $shop->products and detach one by one pivot rows, it's work! and deleted method fired correctly.
foreach($shop->products as $product){
$shop->products()->detach($product->id);
}
