I need get two city names with one query:
For example:
City table:
+---------+----------+
| Pana | Name |
+---------+----------+
| T
With straight SQL you could give each joined table an alias - e.g.
SELECT flights.*
FROM flights as f
JOIN cities as fromCity on fromCity.pana = f.from_city
JOIN cities as toCity on toCity.pana = f.to_city
WHERE f.id = 3 --
With Eloquent, use select() to specify select fields. Also use DB::raw() to use raw SQL (e.g. giving an alias to table like DB::raw('cities as toCity')
.
public function scopePrintQuery($query, $id)
{
$join = $query
-> join(DB::raw('cities as fromCity'), 'fromCity.pana', 'flights.from_city')
-> join(DB::raw('cities as toCity'), 'toCity.pana', 'flights.to_city')
-> where('flights.id', $id)
->select([
'flights.*',
DB::raw('fromCity.name as from_city')
DB::raw('toCity.name as to_city')
]);
return $join->get();
}