yii2在相关模型中排序

时间:2015-08-17 13:25:33

标签: php sorting yii2 models

有关系

型号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}'],        
            ]
        ]); ?>

对gridviewAddr.division.division的gridview进行排序无法正常工作。如何解决?

1 个答案:

答案 0 :(得分:1)

对于相关模型,您必须正确配置dataProvider的setSort函数

您可以在this tutorial中找到正确的信息。

最重要的是你必须在yourModelSearch这样定义$ dataProvider-&gt; setSor(...)函数

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