Laravel查询问题:排除指定team_id的game_teams关联数据
问题:排除指定Team的游戏数据查询错误修复
需求说明
- 前端传入team_id数组
[23,24],需返回游戏数据,且关联的game_teams记录中不能包含team_id为23、24的条目
现有错误代码
$results = Game::with(['gameTeams.teams'])->whereNotIn("team_id", $request->arr_team_ids)->get()->toArray();
数据库表结构
games表
| id | name | | 42 | game 1 | | 43 | game 2 |
teams表
| id | name | | 22 | team 1 | | 23 | team 2 | | 24 | team 3 | | 25 | team 4 | | 26 | team 5 |
game_teams表
| id | game_id | team_id | | 1 | 42 | 22 | | 2 | 42 | 23 | | 3 | 43 | 23 | | 4 | 43 | 24 | | 5 | 43 | 25 | | 6 | 43 | 26 |
预期返回结果
[ { "id": 42, "name": "game 1", "game_teams": [ { "id": 1, "game_id": 42, "team_id": 22, "teams": { "id": 22, "name": "team 1" } } ] }, { "id": 43, "name": "game 2", "game_teams": [ { "id": 5, "game_id": 43, "team_id": 25, "teams": { "id": 25, "name": "team 4" } }, { "id": 6, "game_id": 43, "team_id": 26, "teams": { "id": 26, "name": "team 5" } } ] } ]
问题分析
原代码的whereNotIn("team_id", ...)直接在games表上过滤,但games表根本没有team_id字段,会导致SQL错误或空结果。即便字段存在,这种写法也只是过滤掉关联了指定team的游戏,而非保留游戏但过滤关联记录里的指定team。
正确代码实现
要过滤关联的game_teams数据,需用with的闭包约束关联查询:
$excludeTeamIds = $request->arr_team_ids; $results = Game::with(['gameTeams' => function ($query) use ($excludeTeamIds) { // 过滤game_teams中排除指定team_id的记录 $query->whereNotIn('team_id', $excludeTeamIds)->with('teams'); }])->get()->toArray();
代码解释
- 通过
with的闭包函数,对gameTeams关联添加条件过滤,只保留team_id不在排除列表中的记录 - 闭包内调用
with('teams'),确保关联的teams数据正确加载 - 主查询返回所有游戏,但每个游戏的
game_teams仅包含符合条件的关联记录
如果需要同时排除完全没有符合条件game_teams的游戏(比如某游戏所有关联team都在排除列表),可追加has约束:
$results = Game::has('gameTeams') // 确保游戏至少有一条符合条件的game_teams记录 ->with(['gameTeams' => function ($query) use ($excludeTeamIds) { $query->whereNotIn('team_id', $excludeTeamIds)->with('teams'); }])->get()->toArray();
内容的提问来源于stack exchange,提问作者Hey Peter
相关产品推荐
相关产品推荐

