如何在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()
.
相关文章