我有以下简化表格。
基本上有 User 表、Game 表和 Player 表。每个用户都可以加入游戏,这些游戏都保存在玩家表中。
用户
身份证 | 姓名 |
---|---|
1 | 詹姆斯 |
2 | 彼得 |
3 | 玛丽 |
4 | 凯西 |
5 | 辛迪 |
游戏
User_Id 是主机
身份证 | 标题 | 用户ID |
---|---|---|
1 | 游戏一 | 4 |
2 | 游戏二 | 4 |
3 | 第三场比赛 | 4 |
4 | 第四场比赛 | 5 |
玩家
User_Id 是加入游戏的用户。 一个玩家可以参加多个游戏
身份证 | 用户ID | 游戏_Id | 更新时间 |
---|---|---|---|
1 | 1 | 1 | 2024-01-01 10:05:00 |
2 | 1 | 3 | 2024-01-01 10:07:00 |
3 | 2 | 1 | 2024-01-02 11:15:13 |
4 | 1 | 2 | 2024-01-03 12:05:22 |
5 | 1 | 4 | 2024-02-05 12:05:22 |
我使用以下方法获取已加入当前登录用户游戏的玩家列表,按加入日期降序排列。
$latest_joined_players = Player::with('user', 'game')
->WhereRelation('game', 'user_id', '=', $logged_in_user->id)
->orderBy('updated_at', 'DESC')
->paginate(20);
现在,我的问题是。我还如何获得:
玩家的游戏次数?换句话说,玩家加入了当前登录用户(主机)的游戏有多少个?
玩家的总游戏次数?换句话说,玩家总共参加了多少场比赛(不考虑主机)?
假设logged_in_user = 4,总结的预期结果应如下:
用户ID | 已加入_游戏_计数 | 总加入游戏数 | 加入_日期 |
---|---|---|---|
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 |
非常感谢任何帮助。
$latest_joined_players = Player::with(['user', 'game'])
->select('players.*')
->join('games', 'players.game_id', '=', 'games.id')
->selectSub(function ($query) use ($logged_in_user) {
$query->selectRaw('COUNT(*)')
->from('games')
->where('games.host_id', $logged_in_user->id)
->whereColumn('games.id', 'players.game_id');
}, 'Joined_Game_Count')
->selectSub(function ($query) {
$query->selectRaw('COUNT(*)')
->from('games')
->whereColumn('games.id', 'players.game_id');
}, 'Total_Joined_Game_Count')
->orderBy('players.updated_at', 'DESC')
->paginate(20);
在此查询中:
现在,$latest_joined_players将包含附加列Joined_Game_Count和Total_Joined_Game_Count的玩家,代表登录用户托管的每个玩家玩的游戏数以及登录用户玩的游戏总数分别是每个玩家。