2017-02-28 121 views
1

我需要一个查询得到两个城市名称:如何用Laravel 5.3中的表连接两次创建查询?

例如:

市表:

+---------+----------+ 
| Pana | Name | 
+---------+----------+ 
| THR | Tehran | 
| LON | London | 
+---------+----------+ 

在型号:FROM_CITYTHRTO_CITYLON

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; 
} 

现在,我需要获得from_city名称和to_city在此查询中的名称。

该查询不适用于一个表中的两个连接!

如何创建此查询?

回答

1

对于直接的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 -- 

With Eloquent,使用select()指定选择字段。还可以使用DB::raw()使用原始SQL(如给一个别名表像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(); 
} 
+0

哇,谢谢:-) – mySun

2

,你也可以用雄辩的模型定义的关系。

也为更多详情,请登录https://laravel.com/docs/5.3/eloquent-relationships

箱两型 - 月1日是机票

<?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', 'from_city'); 
    } 

} 

第二个模式是

<?php 
class City extends Model 
{ 
    protected $table = 'city'; 
} 

现在对于获取

Flights::where(id, $id)->with('toCity', 'fromCity')->get(); 
+0

你好,谢谢你帮我,为什么你使用'from_city'为'to_city'功能? – mySun

+0

当您查询时,它指定哪些关系应该用于急切加载。欲了解更多详情,请访问https://laravel.com/docs/5.4/eloquent-relationships#eager-loading – Vipul

相关问题