2015-05-06 77 views
3

我設置了一個API,寧願只在我的數組中的對象,而不是「模型名稱」&「孩子」反覆灑在整個。有沒有辦法做到這一點?我想象一個循環會做的伎倆,但我無法弄清楚。Cakephp發現線程沒有「兒童」

 $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' 
    )); 
+0

哪個版本的Cake?您能否展示您正在使用的查詢查詢的示例以及您希望結果的外觀。 – drmonkeyninja

+0

更新了我的問題。 –

+0

你能舉一個你想要結果數組的樣子嗎?你是不是想和孩子們一樣平躺,與父母一樣的深度? – drmonkeyninja

回答

1

看起來好像您提供的代碼對於3.x和2.x都是非常獨特的,所以我將分享它們的解決方案。

3.X

你可以通過在「兒童」作爲取景器型到你的查詢獲取所有的樹節點的後代的平面列表:

$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') 
)); 

如果您只是想找到你節點的直接孩子,傳遞真實的在你的選擇陣列「直接」鍵:

$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 
)); 

更多信息:

3.x Cookbook for TreeBehavior

3.x findChildren() defined in API

3.x API Info for findChildren()

2.x的

要獲取2.x的所有後代的平面列表,你利用 - >兒童()函數由TreeBehavior類提供:

$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 
) 

相反,只找到直接的後裔,你會通過第二個參數爲真:

$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 
) 

更多信息:

2.x Cookbook for TreeBehavior

2.x children() defined in API

2.x API Info for children()

T他用CakePHP TreeBehavior完成了一個很好的工作,通過使用Tree數據來解決很多痛苦。我希望這個信息幫助!