我有一个 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
。
关于php - Laravel groupBy 然后返回一个计数最高的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54160792/