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

时间:2018-05-28 09:14:52

标签: php arrays yii2

我在类别名称中有一个表,其中包含列id,parent_id和title。 default parent_id为0,如果category是子类别,则在parent_id中输入父ID。

我使用此$category = Category::find()->asArray()->all(); 获取带有activerecord的所有类别 我的类别如下:

$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>

这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:2)

首先选择所有父级:

$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>
相关问题