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

$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

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


当前回答

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子句的文档。

其他回答

我知道这可能是一个老问题,但我刚刚发现自己在一个Laravel 5.7应用程序中实现了这个功能。下面是我的工作。

 $articles = Articles::where("created_at",">", Carbon::now()->subMonths(3))->get();

您还需要使用Carbon

use Carbon\Carbon;

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

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

而在livewire中,略有变化

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

让我用准确的时间戳添加正确的语法

之前

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

$from = date('Y-m-d', strtotime($request->from));
$to = date('Y-m-d', strtotime($request->to));
Reservation::whereBetween('reservation_from', [$from, $to])->get();

注意:如果您以字符串形式存储日期,那么请确保在from和to中传递准确的格式。它将与DB匹配。

如果你的字段是datetime而不是date(尽管它适用于这两种情况):

$fromDate = "2016-10-01";
$toDate = "2016-10-31";

$reservations = Reservation::whereRaw(
  "(reservation_from >= ? AND reservation_from <= ?)", 
  [
     $fromDate ." 00:00:00", 
     $toDate ." 23:59:59"
  ]
)->get();

诀窍在于改变它:

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

to

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

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