Cakephp will find threads without "children"
I am setting up an API and would prefer to just objects in my array instead of "ModelName" and "Children" are repeatedly threaded. Is there a way to do this? I'm guessing the loop will do the trick, but I can't figure it out.
$results = $this->Test->find('threaded', array(
'fields' => array('id', 'parent_id', 'name'),
'order' => array('lft ASC') // or array('id ASC')
));
for ($i = 0; $i <= $this->Test->childCount(1); $i++) {
debug($results[$i]['children']);
}
$this->set(array(
'results' => $results,
'_serialize' => 'results'
));
source to share
It seems that the code you provided is not quite unique for both 3.x and 2.x versions, so I will share solutions for each.
3.x
You can get a flat list of all descendants of the node tree by going to "children" as the search type in your query:
$result = $this->Test->find('children', array(
'for' => $record_id, // Notice you have to specify 'for' key!
'fields' => array('id', 'parent_id', 'name'),
'order' => array('lft ASC')
));
If you want to find the direct children of your node, pass true for the "direct" key in your options array:
$result = $this->Test->find('children', array(
'for' => $record_id, // Notice you have to specify 'for' key!
'fields' => array('id', 'parent_id', 'name'),
'order' => array('lft ASC'),
'direct' => true
));
Additional Information:
3.x findChildren () defined in API
3.x API Info for findChildren ()
2.x
To get a flat list of all children in 2.x, you use the -> children () function provided by the TreeBehavior class:
$result = $this->Test->children(
$record_id, // ID of record to find children for
false, // Direct = false
['id', 'parent_id', 'name'], // Fields to include in query
'lft ASC' // Order
)
Conversely, to find only direct descendants, you must pass the second argument as true:
$result = $this->Test->children(
$record_id, // ID of record to find children for
true, // Direct = true
['id', 'parent_id', 'name'], // Fields to include in query
'lft ASC' // Order
)
Additional Information:
2.x children () defined in the API
2.x API Information for Kids ()
CakePHP's TreeBehavior does a great job of taking a break from many of the problems when working with Tree data. Hope this information helps!
source to share