As title says: How do I calculate a node's depth in a parent-child model? I'll need the depth to, among other things, create the indent in my list (coded with PHP).
Thank you in advance.
As title says: How do I calculate a node's depth in a parent-child model? I'll need the depth to, among other things, create the indent in my list (coded with PHP).
Thank you in advance.
That depends on the actual implementation of your hierarchy in the database. If you are using nested sets model (http://dev.mysql.com/tech-resources/articles/hierarchical-data.html) you can retrieve the full parent-to-child path via a single select.
Update: Ok, since you're going with adjacency list model I suggest to store node level in the table. Not only will it give you the node depth in one query, but it will also allow you to retrieve the entire path to that node in one query (albeit that query would have to be dynamically generated):
SELECT n1.name AS lvl1, n2.name as lvl2, n3.name as lvl3, ..., nN.name as lvlN
FROM nodes AS n1
JOIN nodes AS n2 ON n2.parent_id = n1.id
JOIN nodes AS n3 ON n3.parent_id = n2.id
...
JOIN nodes AS nN ON nN.parent_id = n(N-1).id
WHERE nN.id = myChildNode;
Since you know that your node is on level N there's no need for left joins and, given appropriate indexes on id / parent_id this should be reasonably fast.
The downside to this approach is that you'll have to keep node level updated during node moves, but that should be reasonably straightforward and fast as you would only do it for the node itself and its children - not for the majority of the table as you would do with nested sets.