php - 如何使用 Laravel 和 Eloquent 在两个日期之间进行查询?

标签 php laravel laravel-5 orm

我正在尝试创建一个显示从特定日期到特定日期的报告的报告页面。这是我当前的代码:

$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 子句:whereInwhereNotInwhereNullwhereNotNullwhereDate, whereMonth, whereDay, whereYear, whereTime, whereColumn , whereExists, whereRaw.

Laravel docs about Where Clauses.

关于php - 如何使用 Laravel 和 Eloquent 在两个日期之间进行查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33361628/

相关文章:

javascript - 如何过滤 belongsToMany 关系?拉维尔 5.4

php - 图片定位不正确

php - Composer 安装实际上并不安装库

php - laravel 在创建父模型后使用 with() vs load() 进行预加载

javascript - 如何制作没有标记的谷歌地图地点搜索框?

laravel - .editorconfig 文件夹特定的配置

php - Laravel 5.1 防止 CSRF 不匹配抛出异常

php - 创建 2x1 矩阵系统

php - 将默认参数作为 null 发送并使用函数中设置的默认值

php - 使用 Ajax 和 Jquery 设置 Iframe 目标?