nestedSet - parent/child nodes

对着背影说爱祢 提交于 2019-12-23 04:53:33

问题


I am currently working on outputting a heirarchy in terms of a navigation menu from a nestedSet in Doctrine.

I have a number of parents that then have several children.

At the moment in time, there are only 2 levels: Parent and Child (no grandchildren).

I have the following code:

//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) ?>

This renders out:

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

Which is great.

The problem is, that I'd like my URLs to match the parent/child relationship.

Thus the URL for Child Node 2, would be /parent-node-1/child-node-2 (these as slug fields).

So any child of a parent, needs to have the parent node's route slug as well.

I hope that make sense?

Thanks


回答1:


Well, one way to hadle this is to use Doctrine_Core::HYDRATE_RECORD_HIERARCHY hydration, which allows you to call methods on your nodes.

Now you can create a custom method for a node:

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;
  }
}

And call it in template like this:

<a href="<?php echo $node->getUrl() ?>"><?php echo $node['name'] ?></a>


来源:https://stackoverflow.com/questions/5994668/nestedset-parent-child-nodes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!