gpt4 book ai didi

php - Laravel 4 查询生成器(连接)

转载 作者:行者123 更新时间:2023-11-30 22:56:09 27 4
gpt4 key购买 nike

我的数据库中有这些表,即“airport”和“route”,“airport”的id是“route”中的外键(即Origin,Destination)。

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

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

到目前为止,这是我在 Controller 中的查询,它只返回“起点、终点”

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"

任何建议都可以!

最佳答案

所以 - 您想要提取特定机场 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);

我认为这应该可以解决问题 - 只要您在模型中正确创建关系

关于php - Laravel 4 查询生成器(连接),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26315395/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com