Laravel Eloquent关联WithCount查询:获取玩家游戏参与统计
解决方案
核心思路
要获取需求中的两个统计数据,需通过子查询实现:
Joined_Game_Count:统计玩家在当前登录用户(主机)创建的游戏中的参与次数Total_Joined_Game_Count:统计玩家在所有游戏中的总参与次数
同时保留原查询的关联、筛选、排序及分页逻辑。
Eloquent 实现代码
$loggedInUserId = $logged_in_user->id; $latestJoinedPlayers = Player::with(['user', 'game']) ->whereRelation('game', 'user_id', '=', $loggedInUserId) // 计算当前主机游戏的参与次数 ->selectRaw('player.*, (SELECT COUNT(*) FROM player p1 JOIN game g1 ON p1.game_id = g1.id WHERE p1.user_id = player.user_id AND g1.user_id = ?) AS joined_game_count', [$loggedInUserId]) // 计算所有游戏的总参与次数 ->selectRaw('(SELECT COUNT(*) FROM player p2 WHERE p2.user_id = player.user_id) AS total_joined_game_count') // 重命名时间字段匹配预期结果 ->selectRaw('updated_at AS joined_date') ->orderBy('updated_at', 'DESC') ->paginate(20);
代码说明
- 用
selectRaw结合子查询实现统计,避免多次查询提升性能 - 第一个子查询关联
game表,仅统计当前主机创建的游戏中该玩家的参与次数 - 第二个子查询直接统计该玩家在
player表中的总记录数,即全平台游戏参与次数 - 保留原有的模型关联、主机游戏筛选、倒序排序及分页逻辑
结果验证
当登录用户ID为4时,查询结果与预期一致:
| User_Id | Joined_Game_Count | Total_Joined_Game_Count | Joined_Date |
|---|---|---|---|
| 1 | 3 | 4 | 2024-01-03 12:05:22 |
| 2 | 1 | 1 | 2024-01-02 11:15:13 |
| 1 | 3 | 4 | 2024-01-01 10:07:00 |
| 1 | 3 | 4 | 2024-01-01 10:05:00 |
内容的提问来源于stack exchange,提问作者J K
相关产品推荐
相关产品推荐

