yii2在相关模型中排序 [英] yii2 sorting in related model

查看:319
本文介绍了yii2在相关模型中排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关系

模型Shop.php

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

模型SprShopAddr.php

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

模型SprDivision.php

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

查看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}'],        
            ]
        ]); ?>

在gridview上排序,导致字段shopAddr.division.division无法正常工作.如何解决?

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

推荐答案

对于相关模型,必须正确配置dataProvider的setSort功能

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

您可以在最重要的部分是您必须像这样

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

这篇关于yii2在相关模型中排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆