Sunday, 11 August 2013

Complicated queries with php

Complicated queries with php

I got the following tables with some data in them:
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 grandson2 2
+----------------------+
Products2categories:
+-----------------------------+
| id |product_id | category_id|
|_______________________________
| 1 1 3
| 2 1 2
| 3 1 1
+-----------------------------+
Basically, there are products, categories and a table which match the
product to the categories.
As you can see, every product can be related to several categories, just
like in the example above where the product with the id of 1 (pen) is
related to categories: 1,2,3.
That's how the database is build. NOTE: there can be ONLY 3 levels per
category, which means, grandson and grandson2 can't be parents.
Now, what I'm struggling with is the delete functionallity.
I want to choose from a list a category, the category can be a grandfather
category, mabe a father category, or even a grandson category. Once I
click on the delete button, I would like to delete the following things:
the products related to the category
all of the "son" categories
all of the products that the "son" categories hold
remove the prodcut_id and the category_id from the table Products2Categories
For example:
If I delete the category granny I would like to delete all of the products
related to it, then I would like to delete the "son" category which is dad
and all of the products related to it and unlink it from the table
Products2Categories then, because dad has a "son" I would like to delete
his sons, he actually has 2 of them, grandson and grandson2 and all of the
products related to them and ofcourse unlink them from the
Products2Categories table.
I've been trying to think of a code that can do that for the past 2 days
and I just couldn't come up with any idea, I'm pretty much lost.
Thanks in advance!
NOTE: If you need ANY additional information, please feel free to ask for it!

No comments:

Post a Comment