I have a Shops
table which can have Products
. Other Shops can have the same Products so I used a belongsToMany
relation table ShopsProducts
.
I can add an infinite number of Products to a Shop and remove them by saving the Shop entity including the relation. All works fine, but if I want to unlink all Products from a Shop in my form and save, the relation is of cause empty so the Shop will always have 1 Product that I can't delete over the relation but only directly.
This is what the request looks like from the Shops form with a Product
data => [
'name' => 'some',
'is_active' => '1',
'slug' => 'some',
'product_id' => '',
'products' => [
(int) 5 => [
'id' => '5',
'_joinData' => [
'priority' => '0'
]
]
],
]
And this is the request without
data => [
'name' => 'some',
'is_active' => '1',
'slug' => 'some',
'product_id' => '',
]
What is the cake way to handle this issue?
What's your save strategy?
https://book.cakephp.org/3.0/en/orm/saving-data.html#saving-belongstomany-associations
Try
replace
instead ofappend
.If that doesn't work for you, check in the before() or afterSave() if products->get('products') is empty, if it is manually call a deleteAll() on the join table for that product an shop.