我正在使用Laravel 5.3,目前我正在构建一个包含多个部分的账单。这些部分都返回来自一个表的数据,它们之间唯一的区别是"type"列,该列标识它们将被排序到相应的部分中。对于每个部分,我调用4个查询。
现在,有8个部分。8 × 4,32个SQL查询。
一个部分有4个这样的查询:
$records['data'] = Model::where('type', 'x1')->get();
$records['total_cost'] = Model::where('type', 'x1')->sum('cost');
$records['count'] = Model::where('type', 'x1')->count();
$records['total_duration'] = Model::where('type', 'x1')->sum('duration');
我对每个部分重复同样的操作。我不认为这是正确的方式。
我不知道从这里该往哪里走
就这样做吧:)
$data = Model::groupBy('type')->get();
$totalCost = $count = $totalDuration = [];
$types = ['x1', 'x2'];
foreach($types as $type) {
$totalCost[$type] = $data[$type]->sum('cost');
$count[$type] = $data[$type]->count();
$totalDuration[$type] = $data[$type]->sum('duration');
}
只查询一次:)