Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Esirei's avatar

Help with complex eloquent query

I have the below tables

users
  id
  name

games
  id
  name

tournaments
  id
  name
  game_id

leaderboards
  id
  user_id
  game_id
  tournament_id
  points

I believe the tables are self-descriptive, the leaderboards table holds data of tournaments & games played by a user and the points they got. I want to display a paginated public table on the frontend that gets data from the leaderboards table, filtered by the game selected, it'll display users' name, their total points in the game across different tournaments, and their individual scores for each tournament which is the complicated part here, something like the below.

|     Name     |     Tournament 1     |     T-2     |     T-3     |     Total     |
|    John Doe  |          8           |      5      |      0      |       13      |
|    Jane Doe  |          0           |      6      |      8      |       12      |

This example shows 3 tournaments, but note that the tournaments are not static, more can be added thereby extending this table. If a user does not participate in a tournament(i.e. no record on the tournaments table), they get a zero. Currently what I've been able to do is add a tournaments filter and show just the points for that, along with the total points across all tournaments using the query below. But still, I'll like to make it dynamic, showing all the tournaments and scores for them without having to make use of multiple DB queries or excessive array manipulations.

  Leaderboard::query()
     ->select()
     ->with('user')
     ->groupBy('user_id')
     ->selectSub('sum(points)', 'total')
     ->addSelect([
          'tournament_points' => DB::table('leaderboards', 'sub')
               ->select('points')
               ->where('tournament_id', $id)
               ->whereColumn('leaderboards.user_id', 'sub.user_id')
          ])
     ->orderByDesc('total')
     ->paginate();
0 likes
2 replies
jdc1898's avatar

Have you tried using the hasManyThrough() relationship? Seems like it could be a good approach.

2 likes

Please or to participate in this conversation.