如何在Yii2中显示带有子类别的类别

Masoud92分钟

我在类别名称中有一个表,其中包含列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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

表中带有子类别的类别-PHP + MYSQL

带有子类别的Django类别

带有子类别的Joomla Web链接未显示

显示类别的子类别

如何在wordpress的网格布局中显示带有图像的帖子类别?

jQuery显示具有特定类别的部分,并带有相同类别或子类别的按钮

显示带有子类别的数组中的项目的 DRY-er 方式

如何在prestashop中显示父类别中的子类别?

显示Woocommerce中当前子类别的子类别

如何显示所有子类别的文章?

如何在子类别页面中显示Wordpress类别?

如何在类别下拉列表中显示子类别

如何在magento中显示类别和子类别

sql + php显示带有无限子类别的类别

带有类别和子类别的下拉列表

在WordPress中显示子类别的帖子?

如何在选择列表中显示类别,子类别,子子类别-php / mysql?

如何显示类别中的子类别?

mysql 中带有类别和子类别的减法数据是否可行?

在joomla中显示带有类别的文章名称

Mediawiki API:如何列出类别的所有子类别?

Opencart 2.3.0.2 如何在首页显示特定类别的产品并带有标志

显示带有父类别的类别表

Django中有2个类别的一种模型。如何在html中显示同一模型的另一个类别?

如何在带有类别的Rails中实现bootstrap下拉列表

如何在node.js中读取带有嵌套类别的json文件

如何在 Wordpress 中显示类别的分页?

如何在Wordpress中显示特定类别的帖子

如何在django中显示属于类别的记录