I need get two city names with one query:
For example:
City table:
+---------+----------+
| Pana | Name |
+---------+----------+
| THR | Tehran |
| LON | London |
+---------+----------+
In Model: from_city is THR and to_city is LON
public function scopePrintQuery($query, $id)
{
$join = $query
-> join('cities', 'cities.pana', 'flights.from_city')
-> join('cities', 'cities.pana', 'flights.to_city')
-> where('flights.id', $id)
->get([
'flights.*',
'cities.name as from_city'
??? for to_city?
]);
return $join;
}
Now, I need get from_city name and to_city name in this query.
The query does not work with two joins from one table!
How to create this query?
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();
}
you can also use the eloquent model with defining the relationship.
Also for more detail visit https://laravel.com/docs/5.3/eloquent-relationships
crate two model --
1st is "Flights"
<?php
class Flights extends Model
{
protected $table = 'flights';
/**
* Get the From City detail.
*/
public function fromCity()
{
return $this->hasOne('App\Models\City', 'Pana', 'from_city');
}
/**
* Get the To city state.
*/
public function toCity()
{
return $this->hasOne('App\Models\City', 'Pana', 'to_city');
}
}
2nd Model is "City"
<?php
class City extends Model
{
protected $table = 'city';
}
Now for fetching
Flights::where(id, $id)->with('toCity', 'fromCity')->get();