Laravel 如何筛选活跃赛季俱乐部并按league_id分组查询
解决方案
你只需要借助Laravel集合内置的groupBy()方法即可实现按指定字段分组,以下是不同场景的实现方案:
方法1:最小改动适配原有代码
直接在查询后调用集合的groupBy方法,同时补充活跃赛季不存在的异常处理,避免空对象调用属性报错:
public function clubs_by_active_season() { $season = Season::where('status','active')->first(); // 无活跃赛季时直接返回空数组 if (!$season) { return []; } $clubs = Club::where('season_id', $season->id) ->get() ->groupBy('league_id'); // 按league_id字段分组 return $clubs; }
返回结果为集合类型,外层键是league_id的取值,每个键对应的值是该联赛下所有符合条件的俱乐部列表。
方法2:基于模型关联简化写法
你已经在Season模型中定义了和Club的一对多关联,可以直接通过关联获取数据再分组,代码更简洁:
public function clubs_by_active_season() { $season = Season::where('status','active')->first(); return $season ? $season->club->groupBy('league_id') : []; }
扩展:同时返回关联的联赛信息
如果需要俱乐部附带对应的联赛详情,可以加上with()预加载关联,避免N+1查询问题:
public function clubs_by_active_season() { $season = Season::where('status','active')->first(); if (!$season) { return []; } $clubs = Club::where('season_id', $season->id) ->with('league') // 预加载联赛关联数据 ->get() ->groupBy('league_id'); return $clubs; }
内容的提问来源于stack exchange,提问作者Sermed mayi
相关产品推荐
相关产品推荐

