Yii 分組統計寫法(group by count)

最終寫出的查詢語句:

// 近30天的銷量
    private function last30DaySale($storeIdArr)
    {
        $time_30day = strtotime('-30 days');
        
        $list = Order::find()
            ->andWhere(['in', 'storeId', (array) $storeIdArr])
            ->andWhere(['>', 'createdAt', $time_30day])
            ->andWhere(['in', 'state', [2,3,4,5,6]])
            ->groupBy('storeId')
            ->select('storeId, count(*) as total')
            ->asArray()
            ->all();
        $list = $this->keyBy($list, 'storeId');
        
        return $list;
    }
    
    private function keyBy($arr, $by_key) 
    {
        $key_arr = array_column($arr, $by_key);
        $res_arr = array_combine($key_arr, $arr);
        return $res_arr;
    }

這裏面用到了 where in、where >、group by count(*) 用法。因爲同時用了 groupBy 和 select('storeId, count(*) as total') 進行分組統計,不能直接用 all() 獲取所有的結果,需要先使用 asArray() 轉化再 all()

以下是寫這個查詢所參考的資料:

1、Yii2打印sql語句的寫法

...->createCommand()->getRawSql();

2、yii2 打印sql日誌

開啓SQL日誌的方法,略麻煩。。

3、yii2學習筆記 ---查詢數據分組統計

$query=Information::find()->groupBy('insertion_time')->alias('a')->select('count(*) as total,a.*')->all();

 4、yii2 where in的用法

->where([  
    'in', 'id', [1, 3, 5, 6]
])
->where([  
    'not in', 'id', [1, 2, 4, 3]
])

 5、學習使用yii2框架查詢數據庫model的超詳解說並舉例

 較全面!TP也需要一篇這樣的查詢語句使用的總結文章!

6、活動記錄(Active Record)-Yii權威指南

官方的,沒啥好說的,慢慢看。

 

-EOF-

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章