最終寫出的查詢語句:
// 近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()。
以下是寫這個查詢所參考的資料:
...->createCommand()->getRawSql();
開啓SQL日誌的方法,略麻煩。。
$query=Information::find()->groupBy('insertion_time')->alias('a')->select('count(*) as total,a.*')->all();
->where([
'in', 'id', [1, 3, 5, 6]
])
->where([
'not in', 'id', [1, 2, 4, 3]
])
5、學習使用yii2框架查詢數據庫model的超詳解說並舉例
較全面!TP也需要一篇這樣的查詢語句使用的總結文章!
官方的,沒啥好說的,慢慢看。
-EOF-