在 Yii2(网格视图)getter 参数中对计算字段进行排序



我如何按字段对行进行排序,我从这样的模型获取者那里得到

* Returns the score for this team
*/
public function getScore() {
$score = 0;
if (!empty($this->bonus_points)) {
$score += $this->bonus_points;
}
foreach (Attempt::find()->where(['team_id' => $this->id, 'marked' => 1])->all() as $attempt) {
$score -= $attempt->cost;
$score += $attempt->reward;
}
return $score;
}

查看代码

GridView::widget([
'id' => 'quickfire-grid',
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'filterPosition' => GridView::FILTER_POS_HEADER,
'tableOptions' => [
'class' => 'table'
],
'layout' => "{summary}n{items}n{pager}",
'columns' => [
['class' => 'yiigridCheckboxColumn'],
'name',
[
'attribute' => 'bonus_points',
'label' => 'Adjustment',
'filter' => false
],
[
'attribute' => 'score',
'label' => 'Score',
'filter' => false,
],
[
'label' => 'Adjust score',
'format' => 'raw',
'value' => function ($data) use ($game) {
return Html::input('text', 'score-' . $data->id, '0', ['id' => 'score-' . $data->id]) . ' ' . Html::a('Adjust score', '#', ['class' => 'btn btn-danger btn-adjust-score', 'data-team-id' => $data->id, 'data-href' => Url::toRoute(['adjust-scores', 'game_id' => $game->id, 'skipConfirmation' => true])]);
},
],
],
]);

是否可以按分数字段对网格进行排序?我认为需要添加一些JavaScript代码。我已经阅读了这篇文章,但没有解决方案 https://www.yiiframework.com/wiki/621/filter-sort-by-calculatedrelated-fields-in-gridview-yii-2-0。

Team::find()->select(['total_score' => 'ifnull(s.score, 0)+team.bonus_points'])
->leftJoin([
's' => Attempt::find()
->select('team_id, SUM(reward-cost) as score')
->where(['marked' => 1])
->groupBy('team_id')
], 's.team_id=team.id')
->orderBy('total_score')

像这样的东西(根据您的需要修改选择...

最新更新