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-

 

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