I don't understand why this isn't working:
Device::with(['travel.move.position' => function($q) use ($start, $end) {
return $q->whereBetween('created_date', [$start, $end]);
}]);
I think it should give me all devices with travel->move->position relations but only those that position.datetime is between $start and $end
I tried something like
Device::whereHas('travel.move.position', function($q) use ($start, $end) {
return $q->whereBetween('created_date', [$start, $end]);
});
and I get the expected result but I don't get the eager relationship.
ADDED QUERY FOR ANSWER 1:
select *
from `devices`
where exists (
select * from `travels`
inner join `travel_info` on `travel_info`.`id` = `travels`.`info_id`
where `devices`.`id` = `travel_info`.`device_id`
and exists (
select *
from `moves`
where `moves`.`travel_id` = `travels`.`id`
and exists (
select * from `positions`
where `moves`.`position_id` = `positions`.`id` and `created_at`
between ? and ?
)
)
Query is perfect (like was the whereHas) but when do the with():
select `travels`.*, `travel_info`.`device_id`
from `travels`
inner join `travel_info` on `travel_info`.`id` = `travels`.`info_id`
where `travel_info`.`device_id` in (?, ?, ?)
....
select * from `moves` where `moves`.`travel_id` in (?, ..., ?)
....
select * from `positions` where `positions`.`id` in (?, ..., ?)
position, not thedevice. So you will still get all devices, but within each device->travel->move relationship, you'll see only positions that match your filter.datetime? Since this is a reserved word in mysql: dev.mysql.com/doc/refman/5.7/en/keywords.html I'm thinking that you might need to quote itwhereBetween('datetime', [$start, $end]);with('travel.move.position')to your second query. It then gives you the expected result plus the eager loaded relationships.created_timeetc =)