如何在yii2中计数和分组 [英] How to count and group by in yii2

查看:31
本文介绍了如何在yii2中计数和分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 yii2 生成以下查询:

I would like to generate following query using yii2:

SELECT COUNT(*) AS cnt FROM Lead WHERE allowed = 1 GROUP BY prompt_location_id,lead_type_id

我试过了:

$leadsCount = Lead::find()
->where('approved = 1')
->groupBy(['promoter_location_id', 'lead_type_id'])
->count();

生成此查询的内容:

SELECT COUNT(*) FROM (SELECT * FROM `lead` WHERE approved = 1 GROUP BY `promoter_location_id`, `lead_type_id`) `c`

在 yii 1.x 中,我会执行以下操作:

In yii 1.x I would've done the following:

$criteria = new CDbCriteria();
$criteria->select = 'COUNT(*) AS cnt';
$criteria->group = array('promoter_location_id', 'lead_type_id');

谢谢!

推荐答案

解决方案:

$leadsCount = Lead::find()
->select(['COUNT(*) AS cnt'])
->where('approved = 1')
->groupBy(['promoter_location_id', 'lead_type_id'])
->all();

并将 public $cnt 添加到模型中,在我的示例中为 Lead.

and add public $cnt to the model, in my case Lead.

正如 Kshitiz 所说,你也可以只使用 yiidbQuery::createCommand().

As Kshitiz also stated, you could also just use yiidbQuery::createCommand().

这篇关于如何在yii2中计数和分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆