A
A
Alexander Verbitsky2018-03-14 16:53:03
Yii
Alexander Verbitsky, 2018-03-14 16:53:03

Yii2. How to display all subcategories?

5aa9275ba113f821808434.png
There is a category table.
For example, I select the CLOTHING category, and therefore, the page should display both "T-shirts" and "Polo shirts" and "sleeveless T-shirts" and "T-shirts with sleeves". That is, all subcategories below the selected one.
So, is it possible to get all these categories (namely those below) with one request?
the result should be:

Array
(
    [0] => Array
    (
        [id] => 1
        [name] => Одежда
    )

    [1] => Array
    (
        [id] => 2
        [name] => футболки
    )

    [2] => Array
    (
        [id] => 3
        [name] => футболки-поло
    )

    [3] => Array
    (
        [id] => 4
        [name] => футболки без рукавов
    )

    [4] => Array
    (
        [id] => 5
        [name] => футболки с рукавами
    )
)

You can, of course, use recursion, but suddenly there is a special way in yii.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Maxim Fedorov, 2018-03-14
@qonand

One request will not solve this problem in any way. You have such a category tree storage model that only recursion can be used here. If you want to select everything with one request, change the tree storage model, for example, to Nested Sets

D
Dmitry, 2018-03-14
@slo_nik

Good afternoon.
Use the model link on itself.

public function getParent()
{
   retun $this->hasMany(ModelName::class, ['parent_id' => 'id']);
}

In the query, use with('parent')
Read more here .

D
Denis, 2018-03-14
@sidni

well, not all the developers of the framework should do it for the programmers)))) I think special. There are no ways

M
Maxim Timofeev, 2018-03-14
@webinar

This type of storage is called Adjacency List.
Here is an extension for yii from PaulZi: https://github.com/paulzi/yii2-adjacency-list
Here I analyzed it in a video: https://youtu.be/1BQrCbLTeuw

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question