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

$now = date('Y-m-d');
$reservations = Reservation::where('reservation_from', $now)->get();

这在普通SQL中所做的是从表中选择*,其中reservation_from = $now。

我在这里有这个问题,但我不知道如何将其转换为雄辩的问题。

SELECT * FROM table WHERE reservation_from BETWEEN '$from' AND '$to

如何将上面的代码转换为雄辩的查询?


当前回答

诀窍在于改变它:

Reservation::whereBetween('reservation_from', [$from, $to])->get();

to

Reservation::whereBetween('reservation_from', ["$from", "$to"])->get();

因为mysql中的日期必须是字符串类型

其他回答

以下方法应该有效:

$now = date('Y-m-d');
$reservations = Reservation::where('reservation_from', '>=', $now)
                           ->where('reservation_from', '<=', $to)
                           ->get();

我遵循了其他贡献者提供的有价值的解决方案,遇到了一个没有人解决的小问题。如果reservation_from是一个datetime列,那么它可能不会产生预期的结果,并且会错过所有日期相同但时间高于00:00:00时间的记录。为了改进上面的代码,一个小的调整是需要像这样。

$from = Carbon::parse();
$to = Carbon::parse();
$from = Carbon::parse('2018-01-01')->toDateTimeString();
//Include all the results that fall in $to date as well
$to = Carbon::parse('2018-05-02')
    ->addHours(23)
    ->addMinutes(59)
    ->addSeconds(59)
    ->toDateTimeString();
//Or $to can also be like so
$to = Carbon::parse('2018-05-02')
    ->addHours(24)
    ->toDateTimeString();
Reservation::whereBetween('reservation_from', [$from, $to])->get();

你可以使用DB::raw(")使列作为日期MySQL使用whereBetween函数如下:

    Reservation::whereBetween(DB::raw('DATE(`reservation_from`)'),
    [$request->from,$request->to])->get();

@masoud,在Laravel,你必须从表单请求字段值。所以,

    Reservation::whereBetween('reservation_from',[$request->from,$request->to])->get();

而在livewire中,略有变化

    Reservation::whereBetween('reservation_from',[$this->from,$this->to])->get();

whereBetween方法验证列的值是否在between之间 两个值。

$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子句:whereNotIn, whereenull, whereNotNull, whereDate, whereMonth, whereDay, whereYear, whereTime, whereColumn, whereExists, whereRaw。

Laravel关于Where子句的文档。