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

$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中的日期必须是字符串类型

其他回答

试试这个:

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

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

根据条件检索:laravel文档

希望这对你有所帮助。

如果你想检查当前日期是否存在于db中的两个日期之间: =>在这里,如果员工的申请从和到日期在今天存在,则查询将获得申请列表。

$list=  (new LeaveApplication())
            ->whereDate('from','<=', $today)
            ->whereDate('to','>=', $today)
            ->get();

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

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

您还需要使用Carbon

use Carbon\Carbon;

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

    Reservation::whereBetween(DB::raw('DATE(`reservation_from`)'),
    [$request->from,$request->to])->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();