[英]Laravel groupBy then return one result with the highest count
我有一个expenses
表,它与Descriptions
有belongsTo
关系。 我只想返回最常用的描述实例。 我的想法是获取最常用的description_id
,然后使用id从数据库中获取相应的Description
。 到目前为止,我想出了这个:
auth()->user()->expenses()->get()->groupBy('description_id');
所以这给了我按description_id
分组的结果。 不确定我是否在正确的轨道上,但不知道从哪里开始。 或者,如果有更合适的方法来实现这一目标。 任何可以引导我进入正确方向的事情都将受到赞赏。
你可以这样试试:
$userWithExpensesWithMaxDescription = auth()->user()->expenses()->with(['descriptions' => function ($query) {
// subquery to get only max count
$query->select('description_id', DB::raw('count(*) as total'))
->groupBy('description_id')
->orderBy('total', 'DESC')
->first();
}])->get();
我想你的Expenses
模型中有关系descriptions
。
如果我理解正确,我认为以下应该有效:
DB::table('expenses')
->where('user_id', auth()->user()->id)
->groupBy('description_id')
->orderByRaw('count(*) DESC')
->value('description_id')
->first();
这将返回最受欢迎的费用的description_id
。
假设你有一个expenses
的关系在你的设置Description
模型和user
关系的建立Expense
模型,你可以这样做:
$description = Description::withCount([
'expenses' => function ($query) {
$query->where('user_id', auth()->id());
}])
->orderBy('expenses_count', 'desc')
->first();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.