Laravel 为什么使用get求和要花这么长时间?
我有一万件物品。 当我Laravel 为什么使用get求和要花这么长时间?,laravel,sum,laravel-5.3,laravel-eloquent,bigdata,Laravel,Sum,Laravel 5.3,Laravel Eloquent,Bigdata,我有一万件物品。 当我sum()不使用get()时,如下所示: $total_salary = Employee::where('year','=', '2017') ->sum('total_salary'); $total_bonus = Employee::where('year','=', '2017') ->sum('total_bonus'); return ['total_salary'=>$total_salary, 'total_bonus
sum()
不使用get()
时,如下所示:
$total_salary = Employee::where('year','=', '2017')
->sum('total_salary');
$total_bonus = Employee::where('year','=', '2017')
->sum('total_bonus');
return ['total_salary'=>$total_salary, 'total_bonus'=>$total_bonus];
$query = Employee::where('year','=', '2017')
->get();
$data['total_salary'] = $query->sum('total_salary');
$data['total_bonus'] = $query->sum('total_bonus');
return $data;
需要6秒钟
当我使用get()
时,如下所示:
$total_salary = Employee::where('year','=', '2017')
->sum('total_salary');
$total_bonus = Employee::where('year','=', '2017')
->sum('total_bonus');
return ['total_salary'=>$total_salary, 'total_bonus'=>$total_bonus];
$query = Employee::where('year','=', '2017')
->get();
$data['total_salary'] = $query->sum('total_salary');
$data['total_bonus'] = $query->sum('total_bonus');
return $data;
需要20秒。
我怎样才能在不等待这么长时间的情况下使用
sum()
和get()
但原因是第二个是和藏书馆做汇总,费用太高了。
当您在get
函数之后调用sum时,您正在使用illumb\Support\Collection
进行sum,这就是为什么它花费了这么多时间
让我们使用数据库对其求和:
$result = Employee::where('year','=', '2017')
->select(
\DB::raw('sum(total_salary) as total_salary'),
\DB::raw('sum(total_bonus) as total_bonus')
)
->get();
echo $result->total_salary;
echo $result->total_bonus;
您忘记在where()之前添加all()
condition@Advaith,我用