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!
Without adding the
$cnt
property to modelSolution:
and add
public $cnt
to the model, in my case Lead.As Kshitiz also stated, you could also just use
yii\db\Query::createCommand()
.You can get the count by using count() in the select Query
Reference Link for various functions of select query
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:
Calling count on the property of the Category will return the record count:
Calling count on the function will return 1:
If you are just interested in the count, use
yii\db\Query
as mentioned by others. Won't require any changes to your model:Here's a link to the Yii2 API documentation