I have the following situation:
A data model representing locations
A data model representing keys
A data model representing single key queries called 'key_queries'
Each key has multiple key queries.
Each key query is associated with a single key.
Each key query is also associated with a single location.
I could get the latest key query from the Key model using the latestQuery
public function latestQuery(): HasOne
{
return $this->hasOne(KeyQuery::class)->ofMany('created_at', 'max');
}
and the location of that key with
public function location(): BelongsTo
{
return $this->latestQuery->location();
}
Now, I need to associate locations with keys through the latest key for each key. How can I accomplish this?"
The query I was able to create to achieve this purpose is as follows, can you tell me how to reproduce it with eloquent ?
SELECT * FROM keys
WHERE id IN (
SELECT key_id FROM key_queries
WHERE (key_id, created_at) IN (
SELECT key_id, MAX(created_at) AS max_created_at
FROM key_queries
GROUP BY key_id
)
AND location_id = @QUERYPARAM
)