dtsps2098 2014-10-11 13:53
浏览 14

Laravel 4查询生成器(加入)

I have these tables in my database, namely "airport" and "route", the id of "airport" is a foreign key in "route" (i.e. Origin, Destination).

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

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

So far, this is my query in my Controller and it's only returning the "Origin, Destination"

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

What I would like to do is this:

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

Any suggestions will do!

  • 写回答

2条回答 默认 最新

  • drnvcm3949 2014-10-24 13:33
    关注

    So - you want to pull out the model for a specific airport id but only if it goes to the specified destination?

    Your first query will only return the two columns as that's what you told it to return

    You can get the airport easily by:

    Airport::find($id);
    

    Where $id is the id from a user input for example and should be the key. Find will return a collection

    You could also do:

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

    Then if you have a join in your Airport model such as ->hasMany you could then do:

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

    Which will return the airport with the related routes model attached to it

    You can then take that a stage further and query the relationship by:

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

    I think that should do the trick - as long as you create the relationship correctly in the models

    评论

报告相同问题?

悬赏问题

  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接