I've got this DB structure:
Products:
+---------------------------+
|id|name |details |price|cn|
|__|_____|_________|_____|__|
| 1|pen |somethi |100 |10|
| 2|paper|something|30 |11|
+---------------------------+
Categories:
+----------------------------+
|id | name |parent_id |
|____________________________|
|1 | granny | 0 |
|2 | dad | 1 |
|3 | grandson | 2 |
|4 | grandson 2| 2 |
+----------------------------+
Products2categories:
+-------------------------------+
| id | product_id | category_id|
|_______________________________|
| 1 | 1 | 3 |
| 2 | 1 | 2 |
| 3 | 1 | 1 |
+-------------------------------+
As you can see, the table Categories
is "nested" it refers to other colums of it-self.
What I'm trying to achieve by using CASCADE DELETE is that:
When I delete a product, it will be removed from the Products2categories
table as-well. (I have already done this by using a FK with the table products
.id
to products2categories
.product_id
.
So this is one problem solved.
The main problem is as following:
- When I DELETE a category, I would like to delete all of it's "sons", NOTE: a "son" category can has another "son" category such as in the tables that I've given, where
dad
is a son ofgranny
andgrandson and grandson2
are sons ofdad
which means, whenver I will deletegranny
it will also deletedad,granson,grandson2
. Moreover, I want this to ALSO delete ALL of the products that are related to those categories.
I'm pretty sure there is a need of PHP to do that, but I would also like to know what FK's to use, and where.
NOTE: If you need ANY more details, feel free to ask for it.