2014-10-11 84 views
1

我在我的數據庫中有這些表,即「airport」和「route」,「airport」的id是「路由」(即Origin,Destination)中的外鍵。Laravel 4 Query Builder(加入)

Airport 
+-------+-------------+-----------------------+ 
| id | airportcode | Location    | 
+-------+-------------+-----------------------+ 
| 1 | CEB  | Cebu     | 
| 2 | MAN  | Manila    | 
+-------+-------------+-----------------------+ 

Routes 
+-------+-------------+-----------------------+ 
| id | Origin  | Destination   | 
+-------+-------------+-----------------------+ 
| 1 | 1   | 2      | 
| 2 | 2   | 1      | 
+-------+-------------+-----------------------+ 

到目前爲止,這是我在我的控制器查詢,它只是返回「始發地,目的地」

DB::table('airport') 
    ->join('route', 'airport.id','=','route.Origin') 
    ->join('route', 'airport.id','=','route.Destination') 
    ->select('route.Origin', 'route.Destination') 
    ->get(); 

我想這樣做是這樣的:

SELECT 'airport.Location' from airport, route WHERE 'route.Origin' = 'airport.id' AND 'route.Destination' = 'airport.id"

任何建議都可以!

+1

你能澄清你希望是什麼,從你的查詢來獲取?您是否在尋找從特定位置可到達的所有位置,即查詢「宿務」是否會返回「馬尼拉」? – damiani 2014-10-11 14:26:36

+0

我想通過使用路線中的「Origin」和「Destination」列來獲得機場的「地點」... – yowza 2014-10-11 15:14:53

+0

對不起,我對你的意圖還不清楚......你能演示一個示例查詢和您的預期結果? – damiani 2014-10-11 16:16:21

回答

0

所以 - 你想拉出一個特定的機場ID模型,但只有當它去到指定的目的地?

你的第一個查詢只返回兩列,這就是你告訴它返回

您可以輕鬆獲得機場:

Airport::find($id); 

其中$ id是ID從用戶輸入例如,應該是關鍵。查找將返回一個集合

你也可以這樣做:

Airport::where('id','=', $id)->first() //will return the first record - you could also use ->get() to return a collection 

然後,如果你在你的機場模型中加入諸如 - >的hasMany那麼你可以做:

Airport::where('id','=', $id) 
    ->with('routes') 
    ->get() 

哪樣返回機場,並附上與其相關的航線模型

然後,您可以進一步查看關係,並通過以下方式查詢關係:

Airport::find($id)->routes()->where('destination','=',$dest_id); 

我認爲應該做的伎倆 - 只要你在模型中

0

創建正確的關係。如果您使用的是選擇查詢請確保你提到你想要的所有領域。 ...

it's only returning the "Origin, Destination"因爲您在選擇查詢中僅提及了這兩個。

嘗試類似...

DB::table('route') 
    ->select('route.Origin', 'route.Destination','airport.Location') 
    ->leftjoin('airport', function($join) 
         { 
          $join->where('airport.id',array('route.Origin','route.Destination')); 
         // I haven't used it, if any errors pls comment 
         }) 

    ->get(); 

希望這可以幫助你......

相關問題