【问题标题】:Kohana 3.3 ORM - how to find all ancestors in a tree (self-referencing table)Kohana 3.3 ORM - 如何在树中找到所有祖先(自引用表)
【发布时间】:2013-05-06 01:11:47
【问题描述】:

如何使用以下模型查找记录的所有祖先(不仅仅是直接父):

class Model_Category extends ORM {

protected $_belongs_to = array(
        'parent' => array('model' => 'Category', 'foreign_key' => 'category_id'),
);

protected $_has_many = array(
        'children' => array('model' => 'Category', 'foreign_key' => 'category_id'),
);

$category->parent->find() 仅提供直接父级,即使尝试使用递归函数获取父级的父级,它也会抛出 Kohana_Exception: Method find() cannot be called on loaded objects。

这对我来说很自然,我想必须有一种简单的方法来做到这一点 - 我不确定是我自己还是缺少关于 ORM 关系的文档 - 停!

【问题讨论】:

    标签: orm kohana kohana-orm kohana-3.3 self-referencing-table


    【解决方案1】:

    您应该能够使用递归函数或 while 循环来做到这一点

    $current = $category;
    while ($current->parent->loaded())
    {
        //save $current
        $current = $category->parent;
    }
    

    【讨论】:

      【解决方案2】:

      使用Nested Sets。例如,https://github.com/evopix/orm-mptt。它有parents()children()siblings()等特殊方法。当然,这需要在您的数据库表中进行修改。

      【讨论】:

        【解决方案3】:

        好的,原来相关模型实际上是包含在内的,因为如果你这样做了

        $category->parent->parent->name 它将是 $category 的祖父母的名称。

        我的问题是我正在打印 $category->parent->as_array() 并希望在(多维)数组中看到父关系,而 kohana 似乎并非如此。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-01-27
          • 1970-01-01
          • 2012-03-06
          • 2019-06-17
          • 1970-01-01
          • 2012-12-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多