Php 如何在Laravel 5.3中创建两次表连接的查询?
我需要通过一个查询获取两个城市名称: 例如: 城市表:Php 如何在Laravel 5.3中创建两次表连接的查询?,php,mysql,laravel,eloquent,laravel-5.3,Php,Mysql,Laravel,Eloquent,Laravel 5.3,我需要通过一个查询获取两个城市名称: 例如: 城市表: +---------+----------+ | Pana | Name | +---------+----------+ | THR | Tehran | | LON | London | +---------+----------+ 模型中:from_city为THR,to_city为LON 现在,我需要在这个查询中获取from_city name和to_city name 查询无法处理一个表中的
+---------+----------+
| Pana | Name |
+---------+----------+
| THR | Tehran |
| LON | London |
+---------+----------+
模型中:from_city为THR,to_city为LON
现在,我需要在这个查询中获取from_city name和to_city name
查询无法处理一个表中的两个联接
如何创建此查询 使用直接SQL,您可以为每个联接的表指定一个别名,例如
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 --
使用Eloquent可指定选择字段。还可用于使用原始SQL,例如为表提供别名,如DB::raw“cities as toCity”
您还可以使用雄辩的模型来定义关系 如需了解更多详细信息,请访问 板条箱两个模型- 一是航班
<?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');
}
}
您好,谢谢您的帮助,为什么要使用从城市到城市的函数?当您进行查询时,它会指定应该使用哪些关系进行即时加载。有关更多详细信息,请访问
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();
}
<?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');
}
}
<?php
class City extends Model
{
protected $table = 'city';
}
Flights::where(id, $id)->with('toCity', 'fromCity')->get();