You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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_IdJoined_Game_CountTotal_Joined_Game_CountJoined_Date
1342024-01-03 12:05:22
2112024-01-02 11:15:13
1342024-01-01 10:07:00
1342024-01-01 10:05:00

内容的提问来源于stack exchange,提问作者J K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 16:04:58