cakefp树行为删除除子节点之外的父节点


cakephp Tree behavior remove parent node except children

是否可以使用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()或cakeHP中Tree行为的任何其他函数),但从结果中排除有子节点的节点(在我们的例子中是节点B)?

你知道吗?

提前感谢

你可以,但你需要把手弄脏一点,因为我认为这种行为不允许这样做。

关键是,所有没有子节点的节点都应该具有按顺序排列的leftright值。您需要生成这样的查询:

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

通过这种方式,我们要求所有返回的值都是父节点的子节点,并且它们的左值和右值是按顺序排列的,如果节点有子节点,它们就不会是这样。

查看规范,没有具体的方法,因此必须使用children()和childCount()为其构建自己的函数。以下是代码模板(我不使用Cake 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应该包含您想要的内容。

您可以使用以下代码:

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

这是我的cakehp2.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'));
    }

使用此方法(e.i.removeFromTree())将删除或移动节点,但保留其子树,该子树将被重新排序一级。它提供了比删除更多的控制,对于使用树行为的模型,删除将删除指定的节点及其所有子节点。