Failing to find a solution to this question I was wondering if there was a better way of storing data for this problem.
That db structure allows items to be stored in multiple categories, but doesn’t allow easy access to the parent category hierarchy.
What I would like is to have a category relationship such as:
Books
> Novels
> Paperbacks
> Hardbacks
And have an item stored against Paperbacks for instance that would also show up in Novels and Books. So the ‘categories’ actually work more like filters than actual categories.
First of all you need to design your category table with usage of Nested Set architecture. With usage of Nested Sets you will easily select whole branch of categories, and then you will be able to select products for these categories.
So the first table will be:
The second table will be:
And the third table will be:
Now to select all products for whole branch of categories, you need to use query like this:
Nested set operations
Add new node
1st step: update already existed categories
2nd step: insert new category
Delete existing node
1st step: delete node
2nd step: update else nodes