在第一栏的gridview中,我有一个快递列表。我需要计算每个快递的订单数量。在sql中它看起来像
SELECT order_customFields.order_customFields_delivery_method,
sum(case `order`.order_status when 'sent' then 1 else 0 end) paid
FROM order_customFields
INNER JOIN `order` ON order_customFields.order_id = `order`.order_id
WHERE
order_customFields.order_customFields_order_date >= '2016-12-01' AND
order_customFields.order_customFields_order_date <= '2016-12-31'
AND order_customFields.order_customFields_delivery_method = eu_dpd;
如果我使用couriers创建数组并在foreach中执行sql查询,例如
,该怎么办?`$courier = [eu_dpd,eu_dhl,eu_ups]
foreach ($courier as $value) {
SELECT order_customFields.order_customFields_delivery_method,
sum(case `order`.order_status when 'sent' then 1 else 0 end) paid
FROM order_customFields
INNER JOIN `order` ON order_customFields.order_id = `order`.order_id
WHERE
order_customFields.order_customFields_order_date >= '2016-12-01' AND
order_customFields.order_customFields_order_date <= '2016-12-31'
AND order_customFields.order_customFields_delivery_method = $value;
}`
如何在yii2中应用它?
答案 0 :(得分:1)
对于复杂查询,一种简单的方法是基于普通数据库连接的createCommand
$yourModel = Yii::$app->db->createCommand(
"SELECT order_customFields.order_customFields_delivery_method as deliver_method,
sum(case `order`.order_status when 'sent' then 1 else 0 end) paid
FROM order_customFields
INNER JOIN `order` ON order_customFields.order_id = `order`.order_id
WHERE order_customFields.order_customFields_order_date >= '2016-12-01'
AND order_customFields.order_customFields_order_date <= '2016-12-31'
AND order_customFields.order_customFields_delivery_method = '" .$value . "';")->queryOne();
然后您可以将结果称为
echo $yourModel['deliver_method'];
echo $yourModel['paid'];
对于gridview,您可以使用sqlDataProvider并将dataProvider传递给您的视图http://www.yiiframework.com/doc-2.0/yii-data-sqldataprovider.html