关系:
public function category()
{
return $this->belongsTo(Category::class, 'category_id');
}
public function status()
{
return $this->belongsTo(Status::class, 'status_id');
}
查询:
return DB::table('asset_management_system.assets')
->join('asset_management_system.categories', 'asset_management_system.assets.category_id', '=', 'asset_management_system.categories.id')
->select('asset_management_system.categories.name', 'asset_management_system.categories.icon')
->selectRaw('count(asset_management_system.assets.category_id) as count,
sum(case when status_id = 1 then 1 else 0 end) AS assigned,
sum(case when status_id = 2 then 1 else 0 end) AS "stored",
sum(case when status_id = 3 then 1 else 0 end) AS missing,
sum(case when status_id = 4 then 1 else 0 end) AS broken')
->groupBy('asset_management_system.assets.category_id')
->get();
此查询当前返回每个类别的已资产,已存储,已丢失和已损坏资产的计数。我该如何将其转换为雄辩的?
答案 0 :(得分:1)
您的查询完全可以。我相信这是最有效的方法。
或者,您可以使用withCount函数。
我认为您已经拥有了类别模型:
class Category extends Model
{
public function assets()
{
return $this->hasMany(Asset::class);
}
}
$categories = Category::withCount([
'assets',
'assets as assigned_count' => function ($query) {
$query->where('status_id', 1);
},
'assets as stored_count' => function ($query) {
$query->where('status_id', 2);
},
'assets as missing_count' => function ($query) {
$query->where('status_id', 3);
},
'assets as broken_count' => function ($query) {
$query->where('status_id', 4);
},
])
->get();
然后:
$categories->each(function ($category) {
dump($category->assets_count);
dump($category->assigned_count);
dump($category->stored_count);
dump($category->missing_count);
dump($category->broken_count);
});