【问题标题】:Doctrine 1.2 NestedSet properties and relation inheritance from ancestorsDoctrine 1.2 NestedSet 属性和来自祖先的关系继承
【发布时间】:2011-05-12 14:02:56
【问题描述】:

我有一个 Doctrine 1.2 项目,我正在重构该项目,以便使用具有多个根的原则行为 NestedSet 为表提供树结构。

我需要的是从祖先到后代的继承(不是 OO 常识),其中后代从缺少自己的属性的最近祖先那里继承属性。关系也会发生同样的事情。

让我用一个例子来解释:

Category:
  actAs:
    NestedSet:
      hasManyRoots: true
      rootColumnName: root_id
  columns:
    name: string(50)
    another_property: string(50)
    active: boolean
Tag:
  columns:
    value: string(50)
CategoryTag:
  columns:
    category_id: integer
    tag_id: integer

我要执行的是:

  • 检索某个类别是否处于活动状态,这意味着验证是否所有 祖先很活跃
  • 如果给定类别缺少另一个属性,则继承自 存在的最近的祖先
  • 检索给定类别的标签;如果标签丢失,检索它们 来自最近的祖先

为了最大限度地提高速度和灵活性,您认为最好的方法是什么?

【问题讨论】:

    标签: php symfony1 doctrine nested-sets hierarchical-trees


    【解决方案1】:

    嗯,这很简单。只需像这样获取具有您需要的关系的树:

        class ModelTable extends Doctrine_Table
        {
          /**
           * Gets tree element in one query
           */
          public function getModelTree()
          {
    
            $q = $this->createQuery('g')
              ->leftJoin('g.Tags t')
              ->orderBy('g.root_id')
              ->addOrderBy('g.lft')
              ->where('g.root_id NOT NULL')
    ;
            return $q->execute(array(),  Doctrine_Core::HYDRATE_ARRAY_HIERARCHY);
          }
        }
    

    然后,你可以像这样渲染它:

    <?php function echoNode($tree, $parent=null) { ?>
      <ul>
      <?php foreach ($tree as $node): ?>
        <li data-property='<?php echo false != $node['property'] ? $node['property'] : $parent['property']  ?>'>
          <?php echo $node['name'] ?>
          <?php if (count($node['__children']) > 0): ?>
            <?php echo echoNode($node['__children'], $node) ?>
          <?php endif; ?>
        </li>
      <?php endforeach; ?>       
      </ul>
    <?php } ?>
    
    <?php echo echoNode($tree) ?>
    

    注意,如果父节点不存在,您如何从父节点获取“属性”。解决此问题的另一种方法是使用 Doctrine_Core::HYDRATE_RECORD_HIERARCHY。这允许在循环时调用 $nodes 上的方法。您可以创建一个 Model::getClosestProperty() 方法,例如,从最近的父级获取属性。但是,这不如阵列水合有效。

    【讨论】:

      猜你喜欢
      • 2011-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 2012-05-03
      • 1970-01-01
      相关资源
      最近更新 更多