How to count and group by in yii2

こ雲淡風輕ζ 提交于 2019-12-18 18:47:32

问题


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!


回答1:


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().




回答2:


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




回答3:


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




回答4:


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



回答5:


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())


来源:https://stackoverflow.com/questions/24389765/how-to-count-and-group-by-in-yii2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!