显示两个日期之间的所有数据。

3

目前,我正在尝试显示一组不在日期X和日期Y之间的项目。假设book_date_start = 2021-06-15,bookdate_end = 2021-06-20。

这是我的当前查询:

$query->select('fac_query')
->from('facility_booking')
->where('book_date_start', '>=', $newstartdate)
->where('book_date_end', '<=', $newenddate);

基于这点

$newstartdate = 2021-06-13 and $newenddate = 2021-06-19 (Returns 0 records)
$newstartdate = 2021-06-21 and $newenddate = 2021-06-25 (Returns 0 records)
$newstartdate = 2021-06-11 and $newenddate = 2021-06-12 (Returns 0 records)
$newstartdate = 2021-06-13 and $newenddate = 2021-06-25 (Returns 1 records)
$newstartdate = 2021-06-17 and $newenddate = 2021-06-19 (Returns 0 records)

基本上,当我撰写上面的内容时,我意识到我的查询是错误的。由于2021年6月13日小于2021年6月15日(正确),而2021年6月20日大于2021年6月25日(正确),这就是为什么它返回了该记录。
我的问题是: 如果我只想返回在2021年6月15日至2021年6月20日期间选择的记录,该如何编写查询?(我很确定我在过度思考,但我非常迷茫。)我不需要完整的查询或答案,我只希望有人能稍微指点一下,我就可以自己完成了。谢谢大家阅读。

2
请参考以下链接:https://laravel.com/docs/8.x/queries#additional-where-clauses - Kamlesh Paul
谢谢!我意识到我应该只是使用 ->whereBetween('book_date_start', [$newstartdate, $newenddate]); 这将允许我检查日期的开始是否在X和Y日期之间。(如果是,它将返回记录)。 - Reece
1个回答

1
请尝试以下查询。
$start_date = Carbon::parse($newstartdate)->format('Y-m-d H:i:s');
$end_date = Carbon::parse($newenddate)->format('Y-m-d H:i:s');

$bookinks = \DB::table('facility_booking')->where([['book_date_start','<=',$start_date],['book_date_end','>=',$end_date]])
              ->orwhereBetween('book_date_start',array($start_date,$end_date))
             ->orWhereBetween('book_date_end',array($start_date,$end_date))->get();

1
谢谢!这正是我想要的。现在我终于明白了,我的原始查询只检查日期是否小于和大于。它没有检查任何中间的内容。(这就是为什么一旦有一个日期在中间就会出错)。但是使用您的查询,不仅可以检查大于和小于,而且还添加了另一个检查来查看它是否在两个日期之间。天哪,非常感谢您帮助我理解应该如何编写!! - Reece

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接