2011-05-13 119 views
0

我目前正在从Doctrine中的nestedSet的导航菜单方面着手输出heirarchy。nestedSet - 父/子节点

我有一些父母,然后有几个孩子。

目前,只有2级:父母和子女(没有孙子)。

我有以下代码:

//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字段)。

因此,父母的任何孩子都需要父母节点的路由slu as。

我希望有道理?

感谢

回答

1

好了,这hadle一个方法是使用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> 
+0

这prefectly工作!认为我现在了解nestSet行为! – 2011-05-16 08:07:54

+0

这里需要注意的一点是性能。每次调用getPath()都会导致对db的单独查询。以下是一个查询的替代解决方案:http://stackoverflow.com/questions/6009163/breadcrumb-navigation-with-doctrine-nestedset/6010461#6010461(请参阅我的回答) – Dziamid 2011-05-16 10:19:19

+0

是的,上面的解决方案似乎创建了一些查询。一个会好得多!我会看看你的例子 – 2011-05-16 10:38:21