我有Post
模型和两个相关模型,User
和Comments
。
与User
模型中定义的Comment
和Post
模型的关系:
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',
],
],
]);
使用上面的所有代码,我可以按id
和title
以及userName
对记录进行排序,User
是相关Points
模型的属性。但是我无法对列Comment
进行排序,因为它不是getLeadEarningPerWebmaster()
模型的属性,而是从GridView
方法返回的总和值。我曾尝试在此处阅读Yii 2.0文档http://www.yiiframework.com/doc-2.0/guide-output-data-widgets.html,但排序数据部分仍在开发中。如何根据Points
列对{{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]
],
]),
这应该让你开始。