我使用以下查询来获取值的总和,但在yii2中得到错误。
$sql = 'SELECT sum(bid_item.$quantity), bid_item.product_id FROM
bid_item WHERE bid_item.product_price >=710 AND bid_item.product_id=2
GROUP BY bid_item.product_id';
$bidItem = BidItem::findBySql($sql)->all();
答案 0 :(得分:1)
您可以使用以下命令:
$command = Yii::$app->db->createCommand("SELECT sum(bid_item.$quantity), bid_item.product_id FROM bid_item WHERE bid_item.product_price >=710 AND bid_item.product_id=2 GROUP BY bid_item.product_id");
$result= $command->queryAll();
答案 1 :(得分:0)
使用你的代码是可以的,但你必须改变它:
$sql = 'SELECT sum(bid_item.$quantity) AS sum, bid_item.* '
.'FROM bid_item '
.'WHERE bid_item.product_price >=710 AND bid_item.product_id=2 '
.'GROUP BY bid_item.product_id';
$bidItem = BidItem::findBySql($sql)->all();
在模型类sum
中有BidItem
属性。
class BidItem extends ActiveRecord
{
public $sum;
... all other declarations of the model
}
bid_item.*
需要初始化BidItem
模型的所有其他属性,而sum(bid_item.$quantity) AS sum
是将可计算属性声明为noted in doc的常规方法。