我在类别名称中有一个表,其中包含列id,parent_id和title。默认的parent_id为0,如果category是子类别,则在parent_id中输入父ID。
我得到所有带有activerecord的类别,并带有“$category = Category::find()->asArray()->all();
我的类别”,如下所示:
$category = [
[
'id' => 1,
'parent_id '=> 0,
'title' => 'one',
],
[
'id' => 2,
'parent_id '=> 1,
'title' => 'two',
],
[
'id' => 3,
'parent_id '=> 1,
'title' => 'three',
],
[
'id' => 4,
'parent_id '=> 0,
'title' => 'four',
],
[
'id' => 5,
'parent_id '=> 0,
'title' => 'five',
],
];
我想像这样打印:
<ul>
<li>
one
<ul>
<li>two</li>
<li>three</li>
</ul>
</li>
<li>four</li>
<li>five</li>
</ul>
做这个的最好方式是什么?
首先选择所有父项:
$category = Category::find()->with('childrens')->where(['parent_id'=>0])->all();
在类别模型内编写如下关系:
public function getChildrens()
{
return $this->hasMany(Category::className(), ['parent_id' => 'id'])>andOnCondition('parent_id!=:pid',[':pid' =>0]);;
}
更新您的看法:
<ul>
<?php foreach($category as $cat)?>
<li>
<?=$cat->title?>
<?php if($cat->childrens){?>
<ul>
<?php foreach($cat->childrens as $child){?>
<li><?=$child->title?></li>
<?php }?>
</ul>
<?php } ?>
</li>
<?php }?>
</ul>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句