Eloquent/October 'many-to-many' 关系 - 如何通过相关数据进行搜索?
Eloquent/October 'many-to-many' relation - how to search by related data?
这是模型的简化视图和数据库中的相应列
Route
id
City
id
name
RouteCityPivot
id
city_id
route_id
一条路线只能有两个相关的城市。假设它们是柏林和慕尼黑。
如何通过城市名称查找路线?
这段代码可以找到多条路线其中至少有一个城市:
$route = Route::whereHas('cities', function ($q) use ($from, $to){
q->whereIn('name', [$from, $to]);
})->get();
我怎样才能找到正好有 2 个给定城市的路线 ?谢谢!
根据
解决方法是
$route = Route::whereHas('cities', function ($q) use ($cities){
$q->whereIn('name', $cities);
}, '=', count($cities))->get();
这是模型的简化视图和数据库中的相应列
Route
id
City
id
name
RouteCityPivot
id
city_id
route_id
一条路线只能有两个相关的城市。假设它们是柏林和慕尼黑。 如何通过城市名称查找路线?
这段代码可以找到多条路线其中至少有一个城市:
$route = Route::whereHas('cities', function ($q) use ($from, $to){
q->whereIn('name', [$from, $to]);
})->get();
我怎样才能找到正好有 2 个给定城市的路线 ?谢谢!
根据
解决方法是
$route = Route::whereHas('cities', function ($q) use ($cities){
$q->whereIn('name', $cities);
}, '=', count($cities))->get();