Finding a subtree in a CakePHP Tree

cakephp, mptt, php, tree

Solution

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.

Problem

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.

Original source