有人提出了几个问题,但没有一个问题为这个问题提供了令人满意的解释。
我运行以下查询:
$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_date
和$start
日期范围内有$end
。
如果没有出现,则不返回任何记录。
当出现时,将返回带有所有日期的假期,而不仅仅是约束中的日期。
我理解它在做什么/做了什么,但我不知道如何得到我需要的东西:跟随约束的连接数据的记录。
任何?
答案 0 :(得分:5)
解决方案:
$callback = function($query) use($from, $to) {
$query->whereBetween('start_date', [$from, $to]);
};
$return = Vacation::whereHas('dates', $callback)->with(['dates' => $callback])->get();
答案 1 :(得分:0)
与@stef给出的答案相同,但语法看起来更好(我相信)
$return = Vacation::query()
->whereHas('dates', $datesFilter = function($query) use ($from, $to) {
$query->whereBetween('start_date', [$from, $to]);
})
->with(['dates' => $datesFilter])
->get();