A
A
amorphine2017-12-13 20:25:05
ORM
amorphine, 2017-12-13 20:25:05

Eloquent Many to Many - how to find records that are only related to certain other records?

Simplified View: Model and Properties

Route
id

City 
id
name

RouteCityPivot
id
city_id
route_id

One Route has only 2 City (many to many relationship via pivot table).
Given the names of two cities - such as Berlin and Munich - how can you find the Route containing these two cities?
$route = Route::whereHas('cities', function ($q) use ($from, $to){
            q->whereIn('name', [$from, $to]);
        })->get();

This code will find all Routes that contain at least one of the cities, and you need to find exactly the one where this pair exists.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question