Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count and group by in yii2

Tags:

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!

like image 582
deacs Avatar asked Jun 24 '14 14:06

deacs


People also ask

How to write SQL query in Yii2?

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.

What is query Builder in Yii2?

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.

Is null in Yii2 query?

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.

What is query Builder in PHP?

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.


1 Answers

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

like image 73
deacs Avatar answered Sep 16 '22 12:09

deacs