Let’s say I have a categories table that stores categories. It is implemented in a nested set style(with left and right values).
category_id lft rgt
1 1 6
2 2 5
3 3 4
So category 1 is a parent of category 2. category 2 is a parent of category 3. So its essentially one path from root to leaf.
The category fields of category 1 should be inherited by category 2 which in turn would be inherited by category 3
Now what is the best way to store the fields for a specific category? My solution was to make another table which has the category id foreign key and the fieldname.
category_id fieldname
1 field1
1 field2
2 field3
3 field4
My problem with this approach is that when getting the fields of category 3, I need to get its parent, its parent’s parent and so on until I get to the root node so that I can inherit their fields. It’s not really a bad solution but I wonder if this would work when the category table is very large.
So the problem is basically an optimization problem. Is this an optimal solution?
You can do this using the schema that you have, but joining the two tables together. The beauty of the left/right nest structure is that in one query you can pull out lots of information about the whole hierarchy.
In your instance, you want to pull out all the category IDs with a ‘lft’ equal to or less than the ‘lft’ value for your given level of hierarchy, and join the results against the category ID fields in your fields table.
The query is something like:-
If you only have the category ID to go on then you can also extract the lft value using a subselect or joining the table back on itself.