如何在yii2中计算和分组

时间:2014-06-24 14:51:28

标签: php mysql yii2

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

SELECT COUNT(*) AS cnt FROM lead WHERE approved = 1 GROUP BY promoter_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中我会做以下事情:

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

谢谢!

5 个答案:

答案 0 :(得分:22)

解决方案:

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

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

正如Kshitiz所说,你也可以使用yii\db\Query::createCommand()

答案 1 :(得分:8)

您可以在选择查询

中使用 count()来获取计数
$leadCount = Lead::find()
->where(['approved'=>'1'])
->groupBy(['promoter_location_id', 'lead_type_id'])
->count();

Reference Link用于选择查询的各种功能

答案 2 :(得分:7)

如果您只对计数感兴趣,请使用其他人提到的yii\db\Query。不需要对您的模型进行任何更改:

$leadsCount = (new yii\db\Query())
    ->from('lead')
    ->where('approved = 1')
    ->groupBy(['promoter_location_id', 'lead_type_id'])
    ->count();

以下是Yii2 API documentation

的链接

答案 3 :(得分:0)

不将$cnt属性添加到模型

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

答案 4 :(得分:0)

请注意,如果它对任何人有帮助,则用作属性的getter是可数的(而如果作为函数调用,它将返回1)。在此示例中,我有一个Category类,其中Listings通过listing_to_category加入。要获得该类别的有效批准的清单,我返回一个ActiveQuery,因此:

/**
 * @return \yii\db\ActiveQuery
 */
public function getListingsApprovedActive() {
        return $this->hasMany(Listing::className(), ['listing_id' => 'listing_id'])
                                ->viaTable('listing_to_category', ['category_id' => 'category_id'])
                                ->andWhere(['active' => 1])->andWhere(['approved' => 1]);
}

“类别”属性上的调用计数将返回记录计数:

count($oCat->listingsApprovedActive)

该函数的调用计数将返回1:

count($oCat->getListingsApprovedActive())