2012-02-06 94 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())将删除或移动节点,但保留其子树,将重新调整高一级。它提供了比删除更多的控制,对于使用树行为的模型,它将删除指定节点及其所有子节点。