简体   繁体   中英

Yii2 Sorting on relation ( multivalued column)

I have two tables 1. Name :- id, name, label (text type). 2. Labels :- id, name . In yii2, I have grid view for name mdoule. I want to add search and sort filter for label field.

ex:

table Name : 1, "tom", "1,2,3"

table Label : 1, "label A" 2, "label B", 3, "label C",

In your search models search method insert this

$dataProvider->sort->attributes['label'] = [
    // The tables are the ones our relation are configured to
    'asc'  => ['label.name' => SORT_ASC],
    'desc' => ['label.name' => SORT_DESC],
];

And add this column to your grid view

[
    'filter'    => \yii\helpers\ArrayHelper::map(\common\models\Label::find()->select(['id', 'name'])->asArray()->all(), 'id', 'name'),
    'attribute' => 'label_id',
    'value'     => 'label.name',
    'label'     => Yii::t('backend', 'Label'),
],

Ps.: you can read more about this here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM