【问题标题】:cakephp Tree behavior remove parent node except childrencakephp 树行为删除除子节点外的父节点
【发布时间】:2012-02-06 16:48:23
【问题描述】:

是否可以使用CakePHP Tree Behavior? 从树中删除父节点。例如,假设我有一个这样的节点:

<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() 或 cakePHP 中树行为的任何其他函数),但从结果中排除具有子节点的节点(在我们的例子中为节点 B)?

有什么想法吗?

提前致谢

【问题讨论】:

    标签: php cakephp tree cakephp-1.3 php-5.3


    【解决方案1】:

    你可以,但你需要弄脏你的手,因为我认为这种行为不允许这样的事情。

    关键是所有没有子节点的节点都应该有一个依次排列的leftright 值。你需要像这样发起一个查询:

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

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

    【讨论】:

      【解决方案2】:

      查看规范并没有具体的方法,因此您必须使用 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 应该包含你想要的。

      【讨论】:

      • 对于非常大的结果集,这将涉及对数据库的很多次命中。此外,如果您手头有子记录,您可以检查左右值是否是连续的,无需任何 DB 命中。
      【解决方案3】:

      您可以使用此代码:

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

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 2021-11-15
          • 2022-09-23
          • 1970-01-01
          • 2013-02-04
          • 1970-01-01
          • 2021-06-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多