V
V
Vlad Osadchyi2019-03-18 21:30:23
Yii
Vlad Osadchyi, 2019-03-18 21:30:23

How to sort by two related tables in yii2?

there is such a database, how to sort products in gridView by location name
5c8fe3a37f606601961001.png
UPD: the solution, as always, is in the documentation. in this situation, this method will help.
My Code:
Model Products

public function getLocations()
    {
        return $this->hasMany(Locations::className(), ['id' => 'location_id'])
            ->viaTable('product_to_location', ['product_id' => 'id']);
    }

ProductSearch class
$dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 100,
            ],
            'sort' => ['defaultOrder' => ['name' => SORT_ASC],
                'attributes' => [
                    'location' => [
                        'asc' => ['locations.name' => SORT_ASC],  //locations это имя таблицы в БД, а не имя класса или геттера
                        'desc' => ['locations.name' => SORT_DESC],
                    ]
                ]
            ]
        ]);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dima Pautov, 2016-12-01
@bootd

No to google !
Or so

X
xmoonlight, 2016-12-01
@xmoonlight

svg clip path

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question