我想根据Laravel 5.7中的状态对数据进行计数。我有六个状态(“已分配”,“在途中”,“已开始”,“取消工作程序”,“取消管理员”和“关闭”)。我必须在foreach数据中对此进行查询。
这是我的代码:
$data['list_detail'] = [];
foreach ($listFa as $value) {
$type = $value->type;
$descr = $value->descr;
$c_ass_detail = transaction::where('type', $value->type)
->where('status','like','%Assigned%')
->groupBy('type')
->count();
$c_otw_detail = transaction::where('type', $value->type)
->where('assign_status','like','%On The Way%')
->groupBy('type')
->count();
$c_str_detail = transaction::where('type', $value->type)
->where('assign_status','like','%Started%')
->groupBy('type')
->count();
$c_cbw_detail = transaction::where('type', $value->type)
->where('assign_status','like','%Cancel Worker%')
->groupBy('type')
->count();
$c_cba_detail = transaction::where('type', $value->type)
->where('assign_status','like','%Cancel Admin%')
->groupBy('type')
->count();
$c_cls_detail = transaction::where('type', $value->type)
->where('assign_status','like','%Closed%')
->groupBy('type')
->count();
$total = $c_ass_detail + $c_otw_detail + $c_str_detail + $c_cbw_detail + $c_cba_detail + $c_cls_detail;
array_push($data['list_detail'], array('type'=>$type, 'descr'=>$descr, 'c_ass_detail'=>$c_ass_detail, 'c_otw_detail'=>$c_otw_detail, 'c_str_detail'=>$c_str_detail, 'c_cbw_detail'=>$c_cbw_detail, 'c_cba_detail'=>$c_cba_detail, 'c_cls_detail'=>$c_cls_detail, 'total'=>$total));
}
这是我的查看代码:
<tbody>
@foreach($list_detail_fa as $row)
<tr class="tr_dashboard">
<td>{{ $row['fa_type_cd'] }}</td>
<td>{{ $row['descr'] }}</td>
<td>{{ $row['c_ass_detail'] }}</td>
<td>{{ $row['c_otw_detail'] }}</td>
<td>{{ $row['c_str_detail'] }}</td>
<td>{{ $row['c_cbw_detail'] }}</td>
<td>{{ $row['c_cba_detail'] }}</td>
<td>{{ $row['c_cls_detail'] }}</td>
<td>{{ $row['total'] }}</td>
</tr>
@endforeach
</tbody>
它正在工作,但是我认为这种方式不好,因为刷新页面时,显示数据太慢了。也许是因为有许多相同的查询。因此,如果我只想对每种状态使用一个查询来对数据进行计数,该怎么办?
答案 0 :(得分:0)
您需要在查询中将聚合函数count
与分组依据一起使用。假设您的表名是事务。试试吧!
$typeCounts = DB::table('transactions')
->select('type', 'assign_status', DB::raw('count(type) as type_count'))
->where('type', $value->type)
->groupBy('assign_status')
->get();
然后在树枝中,您可以像这样访问它:
<tbody>
<tr class="tr_dashboard">
@foreach($typeCounts as $row)
<td>{{ $row['type_count'] }}</td>
@endforeach
</tr>
</tbody>
答案 1 :(得分:0)
您为自己过度繁琐:
您只需要:
$allTypes = array_map(function ($value) {
return $value->type;
}, $listFa);
$c_ass_detail = transaction::whereIn('type', $allTypes)
->groupBy('type')
->groupBy('assign_status')
->select('type', 'assign_status', \DB::raw('count(*) as count'))
->get();
然后您的$c_ass_detail
将为每种类型排一行,分配状态,计数组合。