Laravel中基于关联表(Pivot)数据分组统计Availability数量
解决方案
方法1:直接查询中间表(高效推荐)
因为需求是统计指定赛事(Match)下各状态的用户数,直接操作中间表是最高效的方式,无需加载关联模型:
$matchId = 4; // 替换为你要查询的match_id $stats = DB::table('match_user') // 中间表默认命名为两个模型的复数小写拼接,若自定义过请替换为实际表名 ->where('match_id', $matchId) ->select('availability', DB::raw('count(*) as count')) ->groupBy('availability') ->get() ->toArray();
方法2:通过Match模型关联查询
如果已经加载了Match实例,也可以通过Eloquent关联完成统计:
$match = Match::findOrFail($matchId); $stats = $match->users() ->select('availability', DB::raw('count(*) as count')) ->groupBy('availability') ->get() ->toArray();
方法3:强制返回所有状态(含count为0的情况)
如果需要确保三个availability状态都被返回(即使某个状态没有用户),可以手动遍历所有可选值并统计:
$matchId = 4; $statuses = ['available', 'not-available', 'tbc']; $stats = collect($statuses)->map(function ($status) use ($matchId) { return [ 'availability' => $status, 'count' => DB::table('match_user') ->where('match_id', $matchId) ->where('availability', $status) ->count() ]; })->toArray();
关于withCount的说明
withCount主要用于给主模型添加关联计数属性(比如给Match模型添加users_count),但它不太适合直接按pivot字段分组统计。上面的方法更直接满足你的需求。
内容的提问来源于stack exchange,提问作者n8udd
相关产品推荐
相关产品推荐

