Yii2:Gridview 中过滤值列的总和

Yii2: sum of a column on filtered values in Gridview

我可以使用以下代码对 gridview 中的列求和:

<?php
$command = Yii::$app->db->createCommand("SELECT sum(net_total) FROM estimate");
$sum = $command->queryScalar();
echo 'Total ='. $sum;
?>

我在数据库中有一列 discharge_date(这是日期和时间字段),我想更改此列上过滤器的总和。也就是说,如果过滤后的数据显示五个记录,那么我只想要这五个记录的总和。 谢谢。

根据回答更新

代码是这样的:

$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();