php - laravel 查询构造器聚合函数优化
高洛峰
高洛峰 2017-04-11 09:20:45
0
2
664

我想使用laravel构造个聚合查询 SQL语句如下:


select date_format(date_key,'%Y'),sum(sales) as sales,sum(orders) as orders from dataCategory where date_key>='2014-01-01' and date_key <'2017-01-01' group by date_format(date_key,'%Y');

目前是这样构造的:

$array = DataCategory::select(DB::raw("date_format(date_key,'%Y') as date_key,sum(sales) as sales,sum(orders_num) as orders_num,sum(buyer_num) as buyer_num"))
    ->where([['cateid',$cateid],['date_key','>=','2016-06-01']])
    ->groupBy(DB::raw("date_format(date_key,'%Y')"))
    ->get()
    ->toArray();

但这样查询 时间过长。求问怎样优化查询?还是在模型里定义相关方法?作为laravel小白,不是很了解啊。求指导

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
阿神

建议采用laravel中的collection,访问器和修改器修改优化

小葫芦

explain看下语句查询情况

$array = DataCategory::select(DB::raw("date_format(date_key,'%Y') as year,sum(sales) as sales,sum(orders_num) as orders_num,sum(buyer_num) as buyer_num"))
    ->where([['cateid',$cateid],['date_key','>=','2016-06-01']])
    ->groupBy('year'))
    ->get()
    ->toArray();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template