使用laravel 5.6和mysql.我有以下表名vehicles
id name categoryname brandname model
1 juy car toyota 121
2 gty van nissan caravan
3 bgh car bmw 520d
4 hyu van ford max
5 nhj car toyota 121
6 gtr car toyota corolla
7 gtr van nissan caravan
Run Code Online (Sandbox Code Playgroud)
我正在使用以下控制器功能来显示带有bransnames的类别名称
public function filterbrand ()
{
$vehicles = DB::table('vehicles')
->orderBy('categoryname', 'asc')
->get();
return view('vehicles.brand')->withVehicles($vehicles);
Run Code Online (Sandbox Code Playgroud)
并使用以下刀片文件来显示数据
<?php $cat = ""; ?>
@foreach($vehicles->unique('modelname') as $vehicle)
@if($vehicle->categoryname != $cat )
<?php $cat = $vehicle->categoryname; ?>
{{$cat}}
<br><br>
@endif
<ul>
<li>{{$vehicle->brandname}}</li> <br>
</ul>
@endforeach
Run Code Online (Sandbox Code Playgroud)
这是印刷此类型的输出
车
丰田
121
丰田
花冠
BMW
520D
面包车
日产
carvan
福特
最大
但现在我需要打印模型名称,其计数方式如此
汽车
丰田
121(2)
toyota
corolla(1)
bmw
520d(1)
van
nissan
carvan(1)
ford
max(1)
我怎样才能做到这一点?
你可以使用group by计数来获得带有count的模型:
public function filterbrand ()
{
$vehicles = DB::table('vehicles')
->select('categoryname','brandname','model', DB::raw('count(*) as total'))
->orderBy('categoryname', 'asc')
->groupBy('model')
->get();
return view('vehicles.brand')->withVehicles($vehicles);
}
Run Code Online (Sandbox Code Playgroud)