0

我目前正在根据 Doctrine 中的嵌套集的导航菜单输出层次结构。

我有很多父母,然后有几个孩子。

目前,只有 2 个级别:Parent 和 Child(没有孙子)。

我有以下代码:

//actions:
public function executeShow(sfWebRequest $request)
{
  $this->tree = Doctrine::getTable('Model')->getMenuTree();
}

//lib:
class ModelTable extends Doctrine_Table
{
  /**
   * Gets tree element in one query
   */
  public function getMenuTree()
  {

    $q = $this->createQuery('g')
      ->orderBy('g.root_id')
      ->addOrderBy('g.lft')
      ->where('g.root_id NOT NULL');

    return $q->execute(array(),  Doctrine_Core::HYDRATE_ARRAY_HIERARCHY);
  }
}


//template:
<?php function echoNode($tree, $parent=null) { ?>
  <ul>
  <?php foreach ($tree as $node): ?>
    <li data-id='<?php echo $node['id'] ?>'>
      <?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) ?>

这呈现出来:

Parent Node 1
   Child Node 1
   Child Node 2
Parent Node 2
   Child Node 3

这是伟大的。

问题是,我希望我的 URL 匹配父/子关系。

因此,子节点 2 的 URL 将是/parent-node-1/child-node-2(这些作为slug字段)。

因此,父节点的任何子节点也需要具有父节点的路由 slug。

我希望这有意义吗?

谢谢

4

1 回答 1

1

好吧,解决这个问题的一种方法是使用Doctrine_Core::HYDRATE_RECORD_HIERARCHY水合作用,它允许您在节点上调用方法。

现在您可以为节点创建自定义方法:

class Model extends BaseModel
{
  public function __toString()
  {
    return $this->getSlug();
  }
  public function getUrl()
  {
    //getPath uses __toString method to render a node
    $url = $this->getNode()->getPath('/', true);
    return $url;
  }
}

并像这样在模板中调用它:

<a href="<?php echo $node->getUrl() ?>"><?php echo $node['name'] ?></a>
于 2011-05-14T09:58:02.007 回答