Masoud92m
Masoud92m

Reputation: 622

How to show category with sub category in Yii2

I have a table in the name of the category, with columns id, parent_id and title. default parent_id is 0, if category is a sub category, parent id entered in parent_id.

I get all category with activerecord with this $category = Category::find()->asArray()->all(); My category like as follows:

$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',
    ],

];

I want print it like:

<ul>
    <li>
        one
        <ul>
        <li>two</li>
        <li>three</li>
        </ul>
    </li>
    <li>four</li>
    <li>five</li>
</ul>

What is the best way to do this?

Upvotes: 2

Views: 975

Answers (1)

jithin
jithin

Reputation: 920

First select all parent:

$category = Category::find()->with('childrens')->where(['parent_id'=>0])->all();

Write a relation inside category model like below:

public function getChildrens()
{
  return $this->hasMany(Category::className(), ['parent_id' => 'id'])>andOnCondition('parent_id!=:pid',[':pid' =>0]);;
}

update your view :

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

Upvotes: 2

Related Questions