I am trying to create a relationship in Laravel that would provide me with the latest
records only. I have three entities: Game
, Player
and Turn
. I need to be able to create a relationship on Game
to return currentTurns
only.
This is my database:
Players
+--+--------+
|id|name |
+--+--------+
|1 |John Doe|
|2 |Jane Doe|
|3 |John Roe|
+--+--------+
Turns
+--+-------+---------+----+-------------------+
|id|game_id|player_id|roll|created_at |
+--+-------+---------+----+-------------------+
|1 |1 |1 |3 |2020-03-19 08:27:42|
|2 |1 |2 |5 |2020-03-19 08:27:46|
|3 |1 |3 |1 |2020-03-19 08:27:51|
|4 |1 |1 |6 |2020-03-19 08:28:05|
+--+-------+---------+----+-------------------+
Games
+--+--------+
|id|name |
+--+--------+
|1 |Foobar |
+--+--------+
Originally, I would write a raw SQL query somewhat like this:
SELECT * FROM turns WHERE game_id = 1 GROUP BY player_id ORDER BY created_at DESC
I found out that this behaviour has changed since MySQL 5.7. So I found an approach that works without having to disable the strict mode in Laravel.
My current raw query looks like this:
SELECT turns.*
FROM turns
JOIN (
SELECT player_id, max(created_at) as created_at FROM turns WHERE game_id = 1 GROUP BY player_id
) as latest_turns
ON latest_turns.player_id = turns.player_id
AND latest_turns.created_at = turns.created_at
AND game_id = 1
I am not sure if this is the most performant way but I'm looking for ways to achieve this using Eloquent relationship method on Game
class.
<?php
// ...
public function currentTurns(): HasMany
{
return $this->turns(); // ???
}
Any help is welcome, thanks!