2017-02-28 68 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

相關問題