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

Dieuz's avatar
Level 1

Convert SQL query to Eloquent [Solved]

I need help to convert a complex SQL query into eloquent. I have models for all tables (search & airports) in order to join them with With().

The query is:

"SELECT *, fromTable.iata AS from_airport_iata, toTable.iata AS to_airport_iata
FROM ( SELECT * FROM searches ORDER BY searches.id DESC) AS tmp_table   
LEFT JOIN airports fromTable ON fromTable.id = tmp_table.from_airport_id
LEFT JOIN airports toTable ON toTable.id = tmp_table.to_airport_id
GROUP BY tmp_table.to_airport_id
ORDER BY tmp_table.id DESC"

For now I have the following (obviously not doing what I want yet):

$search = new Search;
$search->with('joinAirportFrom')->with('joinAirportTo')->get();

EDIT: I solved the issue.

0 likes
2 replies
Snapey's avatar

What does the query need to do? I don't understand the point of the temporary table.

Some form of flights matrix?

Dieuz's avatar
Level 1

@Snapey : Yes, the tmp_table is needed since I need to order first (ORDER BY searches.id DESC) before Grouping.

Please or to participate in this conversation.