yii2 分组查询的实现方法
在使用yii2开发一个费用结算的小系统,统计费用时,需要进行分组统计,记录下实现方法,供各位道友参考。
需求描述
数据如下表,统计各个成员(mid)的任务提成(fee)总数;
实现方法
在控制器中生成ActiveDataProvider时,在构建的查询条件后添加addGroupBy(['mid']),将数据分组显示。同时在构建查询时计算提成费用合计,需要使用sum()方法来配合实现分组统计,代码如下,my_sum即合计后的各成员的提成费用。
$query = TaskAllot::find()->select('meijuid,mid,sum(fee) as my_sum')->orderBy(['my_sum' => SORT_DESC]);
$query->andFilterWhere([ 'meijuid' => $this->meijuid, 'mid' => $this->mid, ])->addGroupBy(['mid']);
实例
构建dataProvider的查询方法:
/** * Creates data provider instance with search query by meijuname * * @param array $params * * @return ActiveDataProvider */ public function searchbyname($params){ $query = TaskAllot::find()->select('meijuid,mid,sum(fee) as my_sum')->orderBy(['my_sum' => SORT_DESC]); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); $this->load($params); if (!$this->validate()) { return $dataProvider; } $query->andFilterWhere([ 'meijuid' => $this->meijuid, 'mid' => $this->mid, ])->addGroupBy(['mid']); return $dataProvider; }
视图GridView:
<?=GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'showFooter' => true, 'columns' => [ [ 'attribute' => 'meijuid', 'value' => 'namebymeijuid.meijuname', 'filter' => Dramas::find() ->select(['meijuname', 'id']) ->indexBy('id') ->column(), ], [ 'attribute' => 'mid', 'value' => 'namebymid.name', 'filter' => Member::find() ->select(['name', 'id']) ->indexBy('id') ->column(), ], [ 'attribute' => 'fee', 'value' => function ($model) { //$count = TaskAllot::find()->andWhere(['rid' => $model->rid,'tid' => $model->tid])->sum('taskamor'); return '¥' . $model->my_sum; }, 'footer' => TaskAllot::getTotalSum($dataProvider->models,'my_sum'), ], ], ]);?>