Yii2 How to translate SUM SQL function to Query Builder?

这一生的挚爱 提交于 2019-12-24 09:26:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!