To compare columns you use whereColumn()
Jul 21, 2022
3
Level 16
Constrain a with condition by the parent query
So i have a query to get a route someone has taken and where they vitisted
Route::with([
'streets',
'streets.identifiable' //Polymorphic relationship
'streets.identifiable.visits' // <- this is fetching all visits
])->where('status', 'complete')
->where('user_id', '12')
->get();
The problem im having is the street.identifiable.visit relationship is fetching all the visits. I want to constrain it to the parent Route. The visits table has a route_id and I want to constrain it to the Route row, ive tried
'streets.identifiable.visits' => fn(BelongsToMany $query) => $query->where('visits.route_id', 'routes.id');
But that just ends up with error.
Level 16
Update, I fixed it by moving that 1 nested relationship into a load. and using the fetched modal to query against.
$route->load([
'streets.identifiable.visits' => fn($query) => $query->where('route_id', $route->id);
]);
Please or to participate in this conversation.