Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a subtree in a CakePHP Tree

In CakePHP, how do you select just a subtree in a model which actsAs tree?

I tried this, to find the tree headed by the item with label = "My Label"

$this->find("threaded", array(
    "conditions" => array(
        "label" => "My Label"
    )
));

...however looking at the logs, it runs this SQL:

SELECT Menu.id, Menu.parent_id, Menu.lft, Menu.rght, Menu.label, Menu.link
FROM menus Menu
WHERE label = 'My Label'

Which obviously only selects the one node, and not all its children.

like image 513
nickf Avatar asked Oct 21 '09 00:10

nickf


1 Answers

It seems you will have to do it in two steps like this (from the manual):

$parent = $this->Category->find('first', array(
    'conditions' => array('label' => 'My label')
));
$parentAndChildren = $this->Category->find('threaded', array(
    'conditions' => array(
        'Category.lft >=' => $parent['Category']['lft'], 
        'Category.rght <=' => $parent['Category']['rght']
    )
));

You can't use the 'label' => 'my label' condition in the threaded call, since it would only find results that match that condition, parents and children. 'threaded' only rearranges the results of a normal find operation based on the parent_id, so you'll have to supply your own condition of what "children" are by using the lft/rght columns.

like image 147
deceze Avatar answered Oct 25 '22 12:10

deceze