Reputation: 801
i am a new beginner in cakephp. I am trying to do a deletion based on HABTM relationship, but failed. Please help me.
I have three tables: products
, users
and users_products
table.
one product can have many users and one user will have many products. The structure of users_products table is : id
, user_id
, product_id
, renew_id
.
I want to delete all datas in users_products
and products
table when renew_id
meet certain condition, but i do not want to touch anything on the users
table.
I am thinking to write a while loop to delete the records, but afraid will cause many queries and not using cakephp features.
How can i do this?
Upvotes: 0
Views: 1948
Reputation: 7585
You can delete rows from the join just like any other model.
$this->UsersProduct->delete()
or $this->UsersProduct->deleteAll()
If you are using HABTM that relation might not be available so you can define the relations in the models such as User hasMany UsersProduct and Product hasMany UsersProduct, that would allow access from both sides.
You can also use ClassRegistry::init('UsersProduct')->deleteAll()
As a side note, your join model is incorrectly named as it should be ProductsUser based on the conventions, that is join tables are alphabetical order of the join models. Following conventions would give you a table called products_users
Upvotes: 0
Reputation: 1540
For Has Many and HABTM data deletion we prefer this method
//delete(int $id = null, boolean $cascade = true);
$this->Product->delete($id,true);
Cascade will work only when the relationship is defined in Model.
Upvotes: 1