What I'm trying to do is to get top 5 player scores from database. I'm keeping player data in 3 tables, so it's more complicated.
Right now I'm getting scores, but having problem with making them unique per user.
In top 5, one player can appear only once (even if he has top 5 scores on own)
Current query:
DB::table('gameplays', 'gameplay')
->join('users', 'gameplay.user_id', '=', 'users.id')
->join('playerdatas', 'gameplay.user_id', '=', 'playerdatas.user_id')
->select([ DB::raw('DISTINCT(gameplay.user_id)'), 'users.name', 'gameplay.score', 'gameplay.duration', 'gameplay.created_at', 'playerdatas.appearance'])
->where('gameplay.created_at', '>', Carbon::now()->subDays($type))
->where('gameplay.game_id', '=', $game_id)
->orderBy('gameplay.score', 'DESC')
->limit(5)
->get();
So DISTINCT
not work for me, getting all scores not unique per user.
Tryied also with:
->distinct('gameplay.user_id')
->groupBy('gameplay.user_id')
->unique('gameplay.user_id')
It was working with ->unique('gameplay.user_id')
on collection but I would like to make that in query not on collection, because I'm currenlty limiting results to 5, so I would miss some records.
Tables:
games
|id|name |
|1 |game1|
users
|id|name|
| 1|test|
| 2|elo |
| 3| me |
| 4| 3f2|
| 5| 123|
playerdatas
|id|user_id|game_id|appereance|
| 1| 1 | 1 | null |
| 1| 2 | 1 | null |
| 1| 3 | 1 | null |
| 1| 4 | 1 | null |
| 1| 5 | 1 | null |
gameplays
|id|game_id|score|created_at|user_id|
| 1| 1 | 100 |24.07.2020| 1 |
| 1| 1 | 700 |24.07.2020| 1 |
| 1| 1 | 400 |24.07.2020| 2 |
| 1| 1 | 300 |24.07.2020| 3 |
| 1| 1 | 200 |24.07.2020| 1 |
| 1| 1 | 400 |24.07.2020| 2 |
| 1| 1 | 500 |24.07.2020| 3 |
| 1| 1 | 100 |24.07.2020| 2 |
| 1| 1 | 200 |24.07.2020| 3 |
| 1| 1 | 100 |24.07.2020| 1 |
| 1| 1 | 900 |24.07.2020| 2 |
| 1| 1 | 870 |24.07.2020| 3 |