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!
Call yii\db\QueryBuilder to generate a SQL statement based on the current construct of yii\db\Query; Create a yii\db\Command object with the generated SQL statement; Call a query method (e.g. queryAll()) of yii\db\Command to execute the SQL statement and retrieve the data.
The Yii Query Builder provides an object-oriented way of writing SQL statements. It allows developers to use class methods and properties to specify individual parts of a SQL statement.
Yii2 will use "IS NULL" if the $values === null , but in case the value is supplied as an array, and one of those array elements is null, it will not get any special treatment, resulting in the query never matching any records with NULL value.
Introduction. The database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application, and works on all supported database systems.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With