How to count and group by in yii2

2020-03-01 05:24发布

I would like to generate following query using yii2:

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

I have tried:

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

Which generates this query:

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

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');

Thanks!

标签: php mysql yii2
5条回答
2楼-- · 2020-03-01 05:52

Without adding the $cnt property to model

$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();
查看更多
beautiful°
3楼-- · 2020-03-01 05:55

Solution:

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

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

As Kshitiz also stated, you could also just use yii\db\Query::createCommand().

查看更多
ゆ 、 Hurt°
4楼-- · 2020-03-01 05:58

You can get the count by using count() in the select Query

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

Reference Link for various functions of select query

查看更多
姐就是有狂的资本
5楼-- · 2020-03-01 06:15

Just a note, in case it helps anyone, that a getter used as a property is countable (whereas if called as a function it will return 1). In this example, I have a Category class with Listings joined by listing_to_category. To get Active, Approved Listings for the Category, I return an ActiveQuery, thus:

/**
 * @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]);
}

Calling count on the property of the Category will return the record count:

count($oCat->listingsApprovedActive)

Calling count on the function will return 1:

count($oCat->getListingsApprovedActive())
查看更多
女痞
6楼-- · 2020-03-01 06:17

If you are just interested in the count, use yii\db\Query as mentioned by others. Won't require any changes to your model:

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

Here's a link to the Yii2 API documentation

查看更多
登录 后发表回答