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

$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

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


当前回答

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

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

而在livewire中,略有变化

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

其他回答

试试这个:

因为你是基于单列值进行抓取,你可以同样简化你的查询:

$reservations = Reservation::whereBetween('reservation_from', array($from, $to))->get();

根据条件检索:laravel文档

希望这对你有所帮助。

如果你需要在何时有一个datetime字段应该像这样。

return $this->getModel()->whereBetween('created_at', [$dateStart." 00:00:00",$dateEnd." 23:59:59"])->get();

另一种方法:

use Illuminate\Support\Facades\DB;

$trans_from = date('2022-10-08');
$trans_to = date('2022-10-12');
$filter_transactions =  DB::table('table_name_here')->whereBetween('created_at', [$trans_from, $trans_to])->get();

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

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

而在livewire中,略有变化

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

如果你的字段是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();