在yii2中使用sum()以及在相关字段中使用group

时间:2016-04-23 18:11:15

标签: yii2

我有一个表格,有3列 - partyname,billdate,billamount。还有另一个表派对,其中包含partyname和district列。两者都与partyname有关。我可以加入它们并在gridview中显示数据。我想要的是显示如下数据

District    Billdate    Billamount
Kolkata 2016-03-02  20000
Malda   2016-03-02  30000
Jalpaiguri  2016-03-02  30000

Billamount列是属于特定区域的所有各方的总和(金额)。我已阅读Yii2 - getting sum of a columnYii 2 ActiveDataProvider query with ->all() gives "Call to a member function andFilterWhere() on array" errorYii2 Query does not return column sumYii2 - getting sum of a column。但无法实现。请帮忙。 我的搜索是

public function search($params)
    {
        $query = Bills::find();
        $query->joinWith(['parties']);

        //$command = Yii::$app->db->createCommand("SELECT sum(billamount) FROM bills");
        //$sum = $command->queryScalar();
        //echo $sum;
        //$sum = $query->sum('billamount');
        //echo $sum;
        // $sum = (new \yii\db\Query())->from('bills');
        // $sum = $sum->sum('billamount');
        // echo $sum;

        //$sum = $query->sum('billamount');
        //echo $sum;

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

1 个答案:

答案 0 :(得分:3)

使用var for sum alias

扩展模型
class YourModel extends \yii\db\ActiveRecord
{

   public $my_sum;
   .....

然后

 $query = Bills::find()->select('partyname, billdate, sum(billamount) as my_sum)';
 $query->joinWith(['parties']);

在dataProvider中,您可以使用my_sum

来引用总和