How to get sum of different columns in the same query in Yii2


(find123) #1

I’ve implemented mysql query and is working fine but while converting / implementing it in Yii2.
i’m new to Yii2 so, i’m facing some difficulties with active record .

SELECT 
COUNT(price) AS total,
SUM(IF(is_veg = 'Y', 1, 0)) AS veg_count,
SUM(IF(is_not_veg = 'Y', 1, 0)) AS non_veg_count
FROM order_table

I’ve tried doing following

orderTable::find()
  ->select('count(price) as total')
  ->sum(new Expression('IF(is_veg = 'Y', 1, 0)') => 'veg_count')
  ->sum(new Expression('IF(is_not_veg = 'Y', 1, 0)') => 'non_veg_count');

can anyone help me out.!


(find123) #2
orderTable::find()
  ->select(['count(price) as total', 
    "SUM(IF(is_veg = 'Y', 1, 0)) AS veg_count",
     "SUM(IF(is_not_veg = 'Y', 1, 0)) AS non_veg_count"])