Reputation: 604
I have a table products and some tables joint with it by product_id. I want to delete all rows of this product_id from all others tables when a product delete from product table. Now how can doing it in convenience way? I am trying like below:
$productTable = [
'related_products',
'quantities',
'products_tags',
'products_settings',
'products_details',
'categories_products',
];
$tableObj = TableRegistry::get('Products');
$query = $tableObj->query();
$result = $query->deleteAll()
->contain($productTable)
->where(['store_id' => $storeId])
->execute();
Upvotes: 0
Views: 859
Reputation: 5662
In Cakephp there is a dependent property to delete the associated data from other tables.
When the dependent key is set to true, and an entity is deleted, the associated model records are also deleted. In this case we set it to true so that deleting a User will also delete her associated Address.
To use this just create your association
and add dependent
true. For e.g
/* In a Table's initialize method. */
$this->hasMany('Comments', [
'dependent' => true, /* Add this line */
]);
Cake -> Associations - Linking Tables Together
Upvotes: 1