2012-02-06 61 views
0

是否可以使用CakePHP Tree Behavior?從樹中刪除父節點。比方說,比如我有一個這樣的節點:cakephp樹的行爲除了子女移除父節點

<Node A> 
    - child 1 node A 
    - child 2 node A 
    - child 3 node A 
    - <Node B> (which is also a child 4 of Node A) 
     - child 1 node B 
     - child 2 node B 

是否有可能得到節點A的所有chidren(使用chidren(),或在CakePHP樹行爲的任何其他功能),但排除有結果的子節點(在我們的例子中是節點B)?

有什麼想法嗎?

在此先感謝

回答

0

你可以,但你需要讓你的手有點髒,因爲我不認爲行爲允許這樣的事。

關鍵是沒有孩子的所有節點應具有順序的leftright值。你需要掀起這樣的查詢:

SELECT * FROM items WHERE left > (parent's left) AND right < (parent's right) AND right = left + 1 AND parent_id = (parent's ID) 

我們要求所有返回的值是我們的母公司的孩子和他們的左邊和右邊的值是按順序排列,他們不會這樣如果一個節點有孩子。

0

看看規範沒有具體的方法,所以你必須建立你自己的函數,使用children()和childCount()。下面的代碼模板(我不使用PHP蛋糕):

$children = <call TreeBehavior children() method with $id = id of Node A and $direct = true>; 
$children_without_children = array(); 
foreach ($children as $child) { 
    if (<call TreeBehavior childCount() method with $id = $child->id and $direct = true> === 0) { 
     $children_without_children[] = $child; 
    } 
} 

然後$ children_without_children應該包含你想要什麼。

+0

對於非常大的結果集,這將涉及到針對數據庫的** lot **命中。另外,如果你有孩子的記錄,你可以檢查左邊和右邊的值是否連續,否則就不需要任何數據庫命中。 – joeb 2012-02-06 22:03:01

0

您可以使用此代碼:

$this->Node->removeFromTree($id, true); 
0

這裏是代碼從我的CakePHP x項目:

public function delete($id = null) { 
     $this->ProductCategory->id = $id; 
     if (!$this->ProductCategory->exists()) { 
      throw new NotFoundException(__('Invalid product category')); 
     } 
     $this->request->allowMethod('post', 'delete'); 
     if ($this->ProductCategory->removeFromTree($id, TRUE)) { 
      $this->Session->setFlash(__('The product category has been deleted.')); 
     } else { 
      $this->Session->setFlash(__('The product category could not be deleted. Please, try again.')); 
     } 
     return $this->redirect(array('action' => 'index')); 
    } 

使用這種方法(EI removeFromTree())將刪除或移動節點,但保留其子樹,將重新調整高一級。它提供了比刪除更多的控制,對於使用樹行爲的模型,它將刪除指定節點及其所有子節點。