[英]GroupBy from relations using laravel eloquent
我有TypeOfVehicle
model 有很多Vehicle
。
如何按车辆名称类型和计数对所有车辆进行分组以获得类似的结果
[
'Sedan' => 10,
'SUV' => 25,
'Crossover' => 5
]
您可以使用
$counts = DB::table('tablename')
->select('TypeOfVehicle', DB::raw('count(*) as total'))
->groupBy('TypeOfVehicle')
->get();
计数相关模型
如果你想计算一个关系的结果数而不实际加载它们,你可以使用withCount
方法,它会在你的结果模型上放置一个{relation}_count
列。
$typeOfVehicles = App\TypeOfVehicle::withCount('vehicles')->get();
foreach ($typeOfVehicles as $typeOfVehicle) {
echo $typeOfVehicle->vehicles_count;
}
试试这个它给你你的解决方案
$vehicle=Vehicle::all();
$grouped = $vehicle->groupBy(function ($item, $key) {
return substr($item['that_coloumn_name_like_type'], 0);
});
$groupCount = $grouped->map(function ($item, $key) {
return collect($item)->count();
});
//dd($groupCount); to check it work correctly
我假设您在Vehicle
model 中有 eloquent 关系type
,例如:
public function type()
{
return $this->belongsTo('\App\TypeOfVehicle');
}
因此,您可以通过以下方式获取数据:
$result = Vehicle::select('vehicle_type_id', DB::raw('count(vehicle_type_id) as cnt'))
->with('type') // with your type relation
->groupBy('vehicle_type_id') // group by type of vehicle
->get() // get collection from database
->pluck('cnt', 'type.name') // get only needful data
->toArray(); // cast to array if necessary
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.