Ad

Eloquent/October 'many-to-many' Relation - How To Search By Related Data?

- 1 answer

Here's simplified view of Models and according columns from DB

Route
id

City 
id
name

RouteCityPivot
id
city_id
route_id

One Route can have only two related Cities. Let's say they are Berlin and Munich. How can I find a route by the City names?

This code can find several routes which has at least one of the Cities:

$route = Route::whereHas('cities', function ($q) use ($from, $to){
            q->whereIn('name', [$from, $to]);
        })->get();

How can I find the route which has exactly 2 of the given Cities? Thanks!

Ad

Answer

According to the same issue

The solution is

 $route = Route::whereHas('cities', function ($q) use ($cities){
            $q->whereIn('name', $cities);
        }, '=', count($cities))->get();
Ad
source: stackoverflow.com
Ad