In general, there is such a problem, there is a project on yii2 there are categories with infinite nesting and such a task is to bring all the products out of this category and all the categories invested in it. This is how I get the category I am switching to:

$glav_category = Category::find()->where(['translit' => $translit])->one(); 

So I’m looking for categories in it:

 $categorys = Category::find()->where(['parent_id' => $glav_category->id])->all(); 

And here we need to start some cycle that will check the data on the categories for nesting and so on, but I don’t know how to do it. In fact, I just need to get the id of all nested categories after that to get all the goods will not be difficult.

    2 answers 2

    You can get the category tree using recursion.

     function listCategoriesAsTree($indent = '') { $items = []; $categories = Category::find()->all(); foreach ($categories as $category) { $items[$category->id] = $indent . $category->name; $items += self::listCategoriesAsTree($indent . html_entity_decode(' '), $category->id); } return $items; } 

      It basically fits, I just changed it a bit:

       function listCategoriesAsTree($uid = 0) { $items = []; $categories = Category::find()->where(['parent_id' => $uid])->all(); foreach ($categories as $category) { $items[] = $category->id self::listCategoriesAsTree($category->id); } return $items; } 

      Like this.