Laravel 4 Query Builder(加入)

问题描述:

我在我的数据库中有这些表,即“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

所以 - 你想拉出一个特定的机场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); 

我认为应该做的伎俩 - 只要你在模型中

创建正确的关系。如果您使用的是选择查询请确保你提到你想要的所有领域。 ...

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(); 

希望这可以帮助你......