Skip to content Skip to sidebar Skip to footer

Yii2 How To Translate Sum Sql Function To Query Builder?

I have this simple SQL query: SELECT product_name, SUM (product_amount) FROM orders GROUP BY product_name; It will show a list with product names and their amounts. Like this exa

Solution 1:

You need to use yii\db\Expression while selecting as you are trying to call the SQL SUM() function and you need not to quote the function while selecting.

Expression represents a DB expression that does not need escaping or quoting. Expression objects are mainly created for passing raw SQL expressions to methods of yii\db\Query, yii\db\ActiveQuery and related classes.

Change your code to

Orders::find()
    ->select(['product_name', new \yii\db\Expression('SUM(product_amount)')])
    ->groupBy('product_name,product_amount')
    ->all();

Post a Comment for "Yii2 How To Translate Sum Sql Function To Query Builder?"