Fisher
Fisher

Reputation: 685

yii2 sorting in related model

have relation

model Shop.php

  public function getShopAddr()
        {
            return $this->hasOne(SprShopAddr::className(), ['id' => 'shop_addr_id']);
        }

model SprShopAddr.php

public function getDivision()
    {
        return $this->hasOne(SprDivision::className(), ['id' => 'division_id']);
    }

model SprDivision.php

public function getShopAddrs()
    {
        return $this->hasMany(SprShopAddr::className(), ['division_id' => 'id']);
    }

view index.php

 <?= GridView::widget([
            'dataProvider' => $dataProvider,
            //'filterModel' => $searchModel,
            'summary' =>false, 
            'columns' => [
                'location_code',
                [
                    'label' => 'Дивизион',
                    'attribute' => 'division_id',
                    'value' => 'shopAddr.division.division'
                ],
                ['class' => 'yii\grid\ActionColumn', 'template' => '{update}{delete}'],        
            ]
        ]); ?>

sort on gridview for field shopAddr.division.division not working. How to fix it?

Upvotes: 3

Views: 4944

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133360

for related model you must configure properly the setSort function of the dataProvider

You can find the right information in this tutorial.

The most important part is that you must define the $dataProvider->setSor(...) function in yourModelSearch like this

 $dataProvider->setSort([
        'attributes' => [
            'yuorRelatedFieldName' => [
                            'asc' =>    [ $tableRelated . '.yourField' => SORT_ASC ],
                            'desc' =>   [ $tableRelated . '.yourField' => SORT_DESC ],
                            'label' => 'yuorLabel'
            ],                 
        ],
        'defaultOrder' => ['yuorDefaultOrderField' => SORT_ASC],
   ]);

Upvotes: 2

Related Questions