php - 如何在 Yii2 中显示带有子类别的类别
问题描述
我在类别名称中有一个表,其中包含 id、parent_id 和 title 列。默认 parent_id 为 0,如果 category 是子类别,则 parent_id 中输入 parent id。
我使用此 My 类别获得所有具有 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>
推荐阅读
- pandas - 使用 itertools.combinations 生成具有指定顺序的组合
- python - 使用 run_id 作为日志文件的名称而不是时间戳,但 run_id 在运行期间生成
- c - C中的后缀到中缀转换
- uwp - 无法更改 xamarin 表单 UWP 中外壳页面的汉堡菜单图标
- github - 不在本地克隆存储库,而是在服务器中
- python - Windows Server 2019 Selenium 多用户
- c++ - 使用 64 位数据类型时出错
- javascript - 关于 Google 表格的最后修改日期,此 Google 脚本代码有什么问题?
- c# - ASP.NET 如何在没有空格的情况下将 C# 变量与 HTML 的其余部分分开
- r - 在这个非常简单的 R 代码中可以避免 FOR 循环吗?