如何在yii2中计数和分组

How to count and group by in yii2(如何在yii2中计数和分组)
本文介绍了如何在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中计数和分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)