我正在尝试创建一个显示从特定日期到特定日期的报告的报告页面。这是我当前的代码:
$now = date('Y-m-d');
$reservations = Reservation::where('reservation_from', $now)->get();
这在普通 SQL 中的作用是 select * from table where reservation_from = $now
。
我这里有这个查询,但我不知道如何将其转换为 eloquent 查询。
SELECT * FROM table WHERE reservation_from BETWEEN '$from' AND '$to
如何将上面的代码转换为 eloquent 查询?提前谢谢你。
最佳答案
whereBetween
方法验证列的值是否介于
两个值。
$from = date('2018-01-01');
$to = date('2018-05-02');
Reservation::whereBetween('reservation_from', [$from, $to])->get();
在某些情况下,您需要动态添加日期范围。基于 @Anovative的评论你可以这样做:
Reservation::all()->filter(function($item) {
if (Carbon::now()->between($item->from, $item->to)) {
return $item;
}
});
如果您想添加更多条件,则可以使用 orWhereBetween
。如果您想排除日期间隔,则可以使用 whereNotBetween
。
Reservation::whereBetween('reservation_from', [$from1, $to1])
->orWhereBetween('reservation_to', [$from2, $to2])
->whereNotBetween('reservation_to', [$from3, $to3])
->get();
其他有用的 where 子句:whereIn
、whereNotIn
、whereNull
、whereNotNull
、whereDate
, whereMonth
, whereDay
, whereYear
, whereTime
, whereColumn
, whereExists
, whereRaw
.
关于php - 如何使用 Laravel 和 Eloquent 在两个日期之间进行查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33361628/