将原始查询转换为雄辩的 laravel
Posted
技术标签:
【中文标题】将原始查询转换为雄辩的 laravel【英文标题】:Converting raw query to eloquent laravel 【发布时间】:2020-02-24 09:43:21 【问题描述】:关系:
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();
此查询当前返回每个类别的已分配、存储、丢失和损坏资产的计数。我怎样才能把它转换成雄辩的?
【问题讨论】:
你不能。如果你想要一个 Eloquent 对象,那么你必须使用 Eloquent 来实现这一点。如果您有任何 id 或唯一值,您可以基于此获取 Eloquent 对象。 【参考方案1】:您的查询完全没问题。我相信这是最有效的方法。
或者,您可以使用withCount 函数。
我假设您已经获得了 Category 模型:
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);
);
【讨论】:
谢谢!这正是我所需要的。以上是关于将原始查询转换为雄辩的 laravel的主要内容,如果未能解决你的问题,请参考以下文章