views:

91

answers:

2

i am using MySQL with PHP & Doctrine 2.

my question is assuming i am using Modified Preorder Tree Traversal is there a way i can retrieve only immediate children?

+2  A: 

In addition to the lft and rgt values you could also store each child's parent id. One advantage of doing this is that if your lft and rgt values get messed up you can regenerate the tree. It also lets you directly determine the immediate children of a parent node.

GWW
this is definitely is smart idea, i wonder if it might break in any case, say in an update, delete etc. 1st thoughts are no, shld be fine. i just have a wierd feeling this might break somehow
jiewmeng
For deletions, it shouldn't matter (that's assuming if you delete a node, you delete all of it's children too). If you move a node you just have to change it's parent id in addition to its lft and rgt values.
GWW
A: 

As you've discovered, this is not so easy in the MPTT design. You know how to get all the descendants:

SELECT * FROM tree WHERE lft BETWEEN 2 AND 11;

What you need is the set of descendants who have no ancestors that are also descendants of the parent node you're starting at.

SELECT * FROM tree t1 WHERE t1.lft BETWEEN 2 AND 11 
  AND NOT EXISTS (SELECT * FROM tree t2 WHERE t2.lft > 2 AND t2.lft < 11 
                    AND t1.lft > t2.lft AND t1.rgt < t2.rgt);
Bill Karwin
i dont really get the part `t1.lft > t2.lft AND t1.rgt < t2.rgt` ... having a `parent` field seems to simplify it alot more ...
jiewmeng
Yeah I would go with having the parent column. It does make it simpler. I was just giving a solution that is "pure" MPTT design.
Bill Karwin