gpt4 book ai didi

Laravel:过滤嵌套关系?

转载 作者:行者123 更新时间:2023-12-02 01:21:09 26 4
gpt4 key购买 nike

我不明白为什么这不起作用:

Device::with(['travel.move.position' => function($q) use ($start, $end) {
return $q->whereBetween('created_date', [$start, $end]);
}]);

我认为它应该给我所有带有 travel->move->position 的设备关系,但只有那些 position.datetime介于 $start 之间和 $end
我试过类似的东西
Device::whereHas('travel.move.position', function($q) use ($start, $end) {
return $q->whereBetween('created_date', [$start, $end]);
});

我得到了预期的结果,但我没有得到渴望的关系。

添加了对答案 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 ?
)
)

查询是完美的(就像 whereHas 一样)但是何时使用 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 (?, ..., ?)

最佳答案

好的,经过与问题作者的长时间讨论,我们发现问题不是查询本身,而是with()中的关系加载不正确陈述。

我想出了以下似乎返回预期结果的查询。它首先执行主查询以获取与过滤条件匹配的所有设备,然后将相同的过滤器应用于我们需要急切加载的每个关系:

$start = '2016-10-01';
$end = '2016-10-31';

$devices = Device::whereHas('travel.move.position', function($q) use ($start, $end) {
$q->whereBetween('created_at', [$start, $end]);
})->with([
'travel' => function($q1) use ($start, $end) {
$q1->whereHas('move.position', function($q2) use ($start, $end) {
$q2->whereBetween('created_at', [$start, $end]);
});
},
'travel.move' => function($q1) use ($start, $end) {
$q1->whereHas('position', function($q2) use ($start, $end) {
$q2->whereBetween('created_at', [$start, $end]);
});
},
'travel.move.position' => function($q1) use ($start, $end) {
$q1->whereBetween('created_at', [$start, $end]);
}
])->get();

关于Laravel:过滤嵌套关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40152284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com