按GridView Yii Framework 2.0中的相关模型属性排序

时间:2015-01-26 09:22:54

标签: php sorting gridview yii2

我有Post模型和两个相关模型,UserComments

User模型中定义的CommentPost模型的关系:

public function getUser()
{
    return $this->hasOne(User::className(), ['id' => 'user_id']);
}

public function getUserName()
{
    return $this->user->name;
}

public function getComments(){
    return $this->hasMany(Comment::className(), ['comment_id' => 'id']);;
}

public function countCommentPoints() {
    return $this->hasMany(Comment::className(), ['comment_id' => 'id'])->sum('point');
}

我的PostSearch模型如下所示。我省略了代码andFilterWhere(),因为它超出了范围:

class PostSearch extends Post {
    public $userName;

    public function rules()
    {
         return ['userName', 'safe'];
    }

    public function search($params) {
         $query = Post::find();
         $dataProvider = new ActiveDataProvider([
             'query' => $query,
         ]);

         $dataProvider->setSort([
             'attributes' => [
                  'userName' => [
                      'asc' => ['user.name' => SORT_ASC],
                      'desc' => ['user.name' => SORT_DESC],
                  ],
             ],
         ]);

         if (!($this->load($params) && $this->validate())) {
             $query->joinWith(['user']);            
             return $dataProvider;
         }
    }

    return $dataProvider;
}

查看代码:

echo GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        'id',
        'title',
        [
             'attribute' => 'userName',
             'value' => 'userName',
             'label' => 'User Name'
        ],
        [
             'attribute' => 'comment',
             'value' => function($model){
                  return $model->countCommentPoints();
             },
             'label' => 'Points',
        ],
     ],
]);

使用上面的所有代码,我可以按idtitle以及userName对记录进行排序,User是相关Points模型的属性。但是我无法对列Comment进行排序,因为它不是getLeadEarningPerWebmaster()模型的属性,而是从GridView方法返回的总和值。我曾尝试在此处阅读Yii 2.0文档http://www.yiiframework.com/doc-2.0/guide-output-data-widgets.html,但排序数据部分仍在开发中。如何根据Points列对{{1}}进行排序?

1 个答案:

答案 0 :(得分:1)

您可以按相关列对GridView列进行排序,这些列不一定在原始ActiveRecord中。

echo GridView::widget([
'dataProvider' => new ActiveDataProvider([
    'query' => $model->joinWith([
            'comment' => function ($query) {
                    $query->select('SUM(point) AS sum')->from(['comment' => '{{%comment}}']);
            }
    ]),
    'sort' => [
            'attributes' => [
                    'comment.sum' => [
                            'asc' => ['comment.sum' => SORT_ASC],
                            'desc' => ['comment.sum' => SORT_DESC],
                    ]
            ],
            'sortParam' => 'post-sort',
            'defaultOrder' => ['comment.sum' => SORT_ASC]
    ],
]),

这应该让你开始。