如何查询yii中多级菜单的情况?
例如,我有一个这样的表:
menu_name
将跟随它parrent_id
,因此它将形成一个分层菜单
如何在布局上使用Yii DAO
,以便输出为上面的html
我的代码:
<?php
Yii::import('zii.widgets.CMenu', true);
class ActiveMenu extends CMenu
{
public function init(){
$criteria = new CDbCriteria;
$criteria->condition='published=:idpub AND menu_controller=:menu';
$criteria->params=array(':idpub'=>1, ':menu'=>'#');
$items = Menu::model()->findAll($criteria);
echo "<ul id='yw1' class='nav'>";
foreach ($items as $item)
{
echo "<li class='dropdown'>
<a href=".$item->menu_controller." data-toggle='dropdown' class='dropdown-toggle'>
<i class='icon-white icon-list'></i>".$item->menu_name."<b class='caret'></b></a>
</li>";
}
echo "</ul>";
parent::init();
}
}
但在上面的代码中我只得到parents data
。我如何循环以在每个父母菜单中获取childs data
包括此html代码:
<ul id="yw1" class="nav">
<li><a href="/app/home.html"><span class="icon-white icon-tasks"></span> Home</a></li>
<li class="dropdown">
<a href="#" data-toggle="dropdown" class="dropdown-toggle">
<i class="icon-white icon-list"></i>Master<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="expedition"><span class="icon-bar icon-list"></span> Expedition</a></li>
</ul>
<ul class="dropdown-menu">
<li><a href="partner"><span class="icon-bar icon-list"></span> Partner</a></li>
</ul>
<ul class="dropdown-menu">
<li><a href="user"><span class="icon-bar icon-list"></span> User</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" data-toggle="dropdown" class="dropdown-toggle">
<i class="icon-white icon-list"></i>Transaction<b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="processin"><span class="icon-bar icon-list"></span> Process In</a></li>
</ul>
<ul class="dropdown-menu">
<li><a href="processout"><span class="icon-bar icon-list"></span> Process Out</a></li>
</ul>
etc ....
etc ....
etc ....
</li>
</ul>
答案 0 :(得分:1)
您应首先在Menu
模型(Menu.php)中正确设置关系。
public function relations()
{
return array(
'parent' => array(self::BELONGS_TO, 'Menu', 'parent_id'),
'children' => array(self::HAS_MANY, 'Menu', 'parent_id'),
);
}
然后修改代码:
//other codes
foreach ($items as $item)
{
echo "<li class='dropdown'>
<a href=".$item->menu_controller." data-toggle='dropdown' class='dropdown-toggle'>
<i class='icon-white icon-list'></i>".$item->menu_name."<b class='caret'></b></a>
</li>";
foreach ($item->children as $child) {
echo "<ul class='dropdown-menu'>
<li><a href='".$child->menu_controller."'><span class='icon-bar icon-list'></span> ".$child->menu_name."</a></li></u>";
}
}
//other codes