我可以使用以下代码对gridview中的列求和:
<?php
$command = Yii::$app->db->createCommand("SELECT sum(net_total) FROM estimate");
$sum = $command->queryScalar();
echo 'Total ='. $sum;
?>
我在DB中有一列是
discharge_date
(这是日期和时间字段),我想更改此列上的sum on筛选器。也就是说,如果过滤数据显示五条记录,那么我只需要这五条记录的总和。谢谢。
根据答案更新
代码如下:
$query = app\models\Estimate::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$ids = [];
foreach($dataProvider as $i => $model) {
$ids[] = $model->id;}
$command = Yii::$app->db->createCommand("SELECT sum(net_total) FROM estimate WHERE `id` IN ('.implode(',',$ids).')"); // please use a prepared statement instead, just a proof of concept
$sum = $command->queryScalar();
echo $sum;
现在我在网上发现了这个错误
$ids[] = $model->id;}
为Getting unknown property: yii\db\ActiveQuery::id
最佳答案
是否尝试将此查询直接添加到ActiveDataprovider?如here所述,可以指定其他查询部分,这应该是一个可能的解决方案。或者,您可以尝试从ActiveDataprovider中提取结果的id,并使用它们修改辅助查询。
第二种方法的示例:
// You should make sure that the same parameters are passed to
// the GridView's ActiveDataProvider and the Model's find() function
$idQuery = Estimate::find()->all();
$ids = [];
foreach ($idQuery as $i => $model) {
$ids[] = $model['id'];
}
$command = Yii::$app->db->createCommand('SELECT sum(net_total) FROM estimate WHERE `id` IN ('.implode(',',$ids).')'); // please use a prepared statement instead, just a proof of concept
$sum = $command->queryScalar();