[英]Laravel Eloquent multiple whereHas on relationship where column 'order' is higher than the previous whereHas
我正在研究在某些位置停靠的公交路线系统。 路线停靠点按“顺序”列按升序排列,如 1、2、3、4、5 等。
这些是我的表:
公共汽车
id | operator_id | name
1 | 1 | The Big Red Bus
地方(一些虚拟数据只是例如)
id | name | slug | parent_id
1 | Amsterdam | amsterdam |
2 | London | london |
3 | Stockholm | stockholm |
4 | Helsinki | helsinki |
5 | Dam Square | dam-square | 1
路线
id | name
1 | Amsterdam - London
2 | London - Amsterdam
ROUTE_LOCATIONS(地点)
id | route_id | place_id | order | start | end
1 | 1 | 1 | 1 | 1 | 0
2 | 1 | 2 | 2 | 0 | 0
3 | 1 | 3 | 3 | 0 | 0
4 | 1 | 4 | 4 | 0 | 1
用户输入 当我开始搜索以检查我们是否有任何可用的巴士路线时,给定的用户输入是来自 PLACES 表的一个地方 slug。 例如:
下面是我到目前为止尝试过的查询,但我真的不确定如何在实际查询中构建检查/连接以检查“顺序”序列是否为升序。 我只是无法理解它。
$buses = Bus::whereHas('route.locations.place', function ($query) use ($from, $to) {
$query->where('slug', $from)->where('end', 0);
})->whereHas('route.locations.place', function ($query) use ($from, $to) {
$query->where('slug', $to)->where('start', 0);
})->get();
关系结构如下:
BUS hasOne ROUTE
ROUTE belongsToMany BUS
ROUTE hasMany LOCATIONS (ROUTE_LOCATIONS TABLE)
我已经尝试了以下查询,该查询可用于获取可用路由,但我真的很喜欢直接在 laravel eloquent 中使用我的模型来执行此操作,因此我可以轻松地在我的视图中使用这些关系。 我只是不确定如何去做。
下面的查询仅适用于地点 ID 而不是 slug,我真的很喜欢它是一个 slug 而不是 ID。
$routes = DB::select('SELECT R.id, R.name
FROM route_locations L
INNER JOIN routes R ON R.id = L.route_id
WHERE
L.place_id = "'.$from->id.'" AND
EXISTS (SELECT id FROM route_locations F WHERE L.route_id = F.route_id AND F.order > L.order AND F.place_id = "'.$to->id.'")');
有谁知道这是否可能以及如何实现?
谢谢!
您的代码可以重写为:
$busses = Bus::whereHas('route.locations.place', function ($query) use ($from, $to) {
$query->where('slug', $from)
->where('slug', $to)
->where('start', 0)
->where('end', 0);
// here should do a check if the 'order' column is higher than the first wherehas
})->get();
这对我来说没有多大意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.