【问题标题】:Finding a subtree in a CakePHP Tree在 CakePHP 树中查找子树
【发布时间】:2010-12-08 13:31:25
【问题描述】:

在 CakePHP 中,如何在 actsAs 树的模型中只选择一个子树?

我试过这个,找到以label = "My Label" 为首的树

$this->find("threaded", array(
    "conditions" => array(
        "label" => "My Label"
    )
));

...但是查看日志,它会运行以下 SQL:

SELECT Menu.id, Menu.parent_id, Menu.lft, Menu.rght, Menu.label, Menu.link
FROM menus Menu
WHERE label = 'My Label'

显然只选择一个节点,而不是它的所有子节点。

【问题讨论】:

    标签: php cakephp tree mptt


    【解决方案1】:

    看来您必须分两步完成(来自the manual):

    $parent = $this->Category->find('first', array(
        'conditions' => array('label' => 'My label')
    ));
    $parentAndChildren = $this->Category->find('threaded', array(
        'conditions' => array(
            'Category.lft >=' => $parent['Category']['lft'], 
            'Category.rght <=' => $parent['Category']['rght']
        )
    ));
    

    您不能在threaded 调用中使用'label' =&gt; 'my label' 条件,因为它只会找到符合该条件的结果,即父母和孩子。 'threaded' 仅根据 parent_id 重新排列正常查找操作的结果,因此您必须使用 lft/rght 列提供您自己的“孩子”条件。

    【讨论】:

    • 是的,我最终做了几乎完全相同的事情 - 没有在组件中包含此功能似乎很有趣。
    • 我同意,这似乎是一个明显的用例。有-&gt;children(),但没有-&gt;childrenThreaded()。在模型课上闲逛,我想如果你按 id 去的话,你可能可以做$model-&gt;_findThreaded('after', null, $model-&gt;children($id)),但这似乎有点老套。 :o)
    • 感谢解答,我也希望有比这个更简洁的方式。顺便说一句,如果你只想要孩子,你应该使用'conditions' =&gt; array('Category.lft &gt;' =&gt; $parent['Category']['lft'], 'Category.rght &lt;' =&gt; $parent['Category']['rght']) 不再获取父母。
    • 嗨,我如何将它显示到我的视图中?如果我有 10 个级别的孩子,我该如何循环...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多