yii2 sorting in related model

给你一囗甜甜゛ 提交于 2019-12-11 02:58:28

问题


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?


回答1:


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],
   ]);


来源:https://stackoverflow.com/questions/32051633/yii2-sorting-in-related-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!