繁体   English   中英

Laravel group然后返回一个具有最高计数的结果

[英]Laravel groupBy then return one result with the highest count

我有一个expenses表,它与DescriptionsbelongsTo关系。 我只想返回最常用的描述实例。 我的想法是获取最常用的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM