Yii2 - Get Column Amount

I found this in the manual, but have no idea how to implement the same

yii\db\Query::count(); returns the result of a COUNT request. Other similar methods include sum($q) , average($q) , max($q) , min($q) , which support the so-called aggregated data query. $q parameter is required for these methods and can be either a column name or an expression.

Say, for example, I have a table name of 'billing' with columns:

 name amount charge1 110.00 charge2 510.00 Total - 620.00 

How i use

 yii\db\Query::sum('amount'); 

I also tried how

 $command = Yii::$app->db->createCommand("SELECT sum(amount) FROM billing"); yii\db\Query::sum($command); 

but the page generates an error.

Thanks.

+7
yii2
source share
4 answers

The first part of the code you tried is trying to use Query Builder. In this case, you must create an instance of the request, set the target table and then calculate the amount:

Via Query Builder ( http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html ):

 $query = (new \yii\db\Query())->from('billing'); $sum = $query->sum('amount'); echo $sum; 

The second part of the code you tried is trying to use data access objects. In this case, you can write raw SQL to query the database, but you must use queryOne() , queryAll() , queryColumn() or queryScalar() to execute the query. queryScalar() is suitable for aggregate query such as this.

Via data access objects ( http://www.yiiframework.com/doc-2.0/guide-db-dao.html ):

 $command = Yii::$app->db->createCommand("SELECT sum(amount) FROM billing"); $sum = $command->queryScalar(); echo $sum; 
+16
source share

Within the model, the amount can also be obtained using:

 $this->find()->where(...)->sum('column'); 
+15
source share

Hope your model name is Billing

Inside Using the Billing Model

 $this->find()->sum('amount'); 

in other models

 Billing::find()->sum('amount'); 
+5
source share

Yu can directly use the yii query concept in the search model

 $this->find()->from('billing')->where(['column'=>value])->sum('amount'); 
+2
source share

All Articles