关于这个问题已经提出了几个问题,但没有一个问题能为这个问题提供令人满意的解释。
我运行以下查询:
$return = Vacation::whereHas('dates', function ($query) use ($from, $to) {
    $query->whereBetween('start_date', [$from, $to]);
})->get();根据查询日志,这将生成以下SQL。返回结果正确,但JOINed数据有问题。
select * from `vacations` where exists (select * from `vacation_dates` where `vacations`.`id` = `vacation_dates`.`vacation_id` and `start_date` between '2017-08-01 00:00:00' and '2017-08-30 00:00:00')由于没有JOIN,因此相关记录会在随后通过急切加载添加,约束也会丢失。
这个场景涉及到具有多个开始/停止日期的Vacations,我想检查哪些度假具有在$start和$end日期范围内的start_date。
如果没有出现,则不返回任何记录。
当出现一个事件时,将返回包含所有日期的Vacation,而不仅仅是约束中的日期。
我知道它是怎么做的,但我不知道如何才能获得我需要的东西:包含跟随约束的连接数据的记录。
有没有人?
发布于 2017-08-26 20:06:26
解决方案:
$callback = function($query) use($from, $to) {
            $query->whereBetween('start_date', [$from, $to]);
        };
        $return = Vacation::whereHas('dates', $callback)->with(['dates' => $callback])->get();发布于 2019-03-28 23:16:04
与@stef给出的答案相同,但语法更好看(我相信)
$return = Vacation::query()
    ->whereHas('dates', $datesFilter = function($query) use ($from, $to) {
        $query->whereBetween('start_date', [$from, $to]);
    })
    ->with(['dates' => $datesFilter])
    ->get();https://stackoverflow.com/questions/45890719
复制相似问题