问题
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 example:
I want to translate it to Yii2 Query Builder. I don't know how to use the SUM
function. I tried this but it didn't work:
Orders::find()
->select(
[
Orders::tableName() . ".product_name",
(new \yii\db\Query())->sum(Orders::tableName() . ".product_amount")
]
)
->groupBy(
[
Orders::tableName() . '.product_name',
Orders::tableName() . '.product_amount'
]
);
回答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();
来源:https://stackoverflow.com/questions/53083764/yii2-how-to-translate-sum-sql-function-to-query-builder