2014-06-24 73 views
15

我想生成下面的查詢使用yii2計數和:如何組由yii2

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

我曾嘗試:

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

生成此查詢:

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

在yii 1.x我會做以下事情:

$criteria = new CDbCriteria(); 
$criteria->select = 'COUNT(*) AS cnt'; 
$criteria->group = array('promoter_location_id', 'lead_type_id'); 

謝謝!

+0

您可以使用create命令編寫您的mysql查詢 – Kshitiz

+0

請將解決方案作爲答案發布。 – Cthulhu

回答

20

解決方案:

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

,並添加public $cnt這個模型,在我的情況的鉛。

正如Kshitiz所述,您也可以使用yii\db\Query::createCommand()

+0

Oki,成功謝謝 – MrBii

+0

這有效,我必須將公共變量添加到模型類中,並由@deacs提及,並用' - > createCommand() - > queryAll()替換all()方法;'還要注意我的select()方法有多個' - > select(['type,date(significant_timestamp)AS significant_timestamp,COUNT(*)AS size'])' –

5

如果您只是對計數感興趣,請使用其他人提到的yii\db\Query。不會要求您模型中的任何改變:

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

這裏給Yii2 API documentation

5

一個鏈接,您可以通過在SELECT查詢

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

使用計數()得到計數Reference Link用於選擇查詢的各種功能

0

不添加$cnt原型rty 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(); 
+1

請不要僅僅發佈代碼,還要添加幾句話來解釋什麼是關鍵區別在於。 – mkl

+0

但是我們沒有收到ActiveRecords –