Manually Building a Tree in CakePHP

cakephp, php, tree

Solution

The MPTT tree logic is rather simple and well explained in Managing Hierarchical Data in MySQL. In summary, every entry has a left and a right value. Every entry whos left/right values are within another entries left-right range are a descendent of that (latter) element. E.g. the LCD node (5/6) is within the range of its parent node, Televisions (2-9).

(source: mysql.com)

To build the lft/rght values for a "new" tree just set all the `parent_ids` properly and run `$this->Model->recover()` on it. Cake will calculate the lft/rght values for you.

Problem

I'm currently working on building an application in CakePHP. There's a quite extensive existing data set that's conceptually a tree, but wasn't previously stored as one. What I mean by that, is there's no real relationship defined in the data. The problem I'm having is getting it to work correctly with the CakePHP tree behaviour. Because I have to set all the values on existing data - as opposed to Cake setting up the structure as elements are inserted - I need to understand how the lft/rght values work. So, I guess the question is: How does the structure data work, specifically the lft/rght values? How do I set it up so that the data comes out rationally, without inserting them one at a time? It's a 2 level tree, with Sections and sub-sections. Thanks for the help

Original source