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

245

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

$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查询?


reservation_from 中的日期格式是什么?您可以根据此使用 Carbon 值。 - Athi Krishnan
日期格式为TIMESTAMP @AthiKrishnan - wobsoriano
4
这段代码的意思是:查询时间从1975年5月21日至2015年5月21日之间的预订信息,并返回结果。 - Athi Krishnan
15个回答

1

非常感谢Artisan Bay的建议,我阅读了他的评论并使用了wheredate()函数,现在我的答案可以正常工作了。

非常感谢!

public function filterwallet($id,$start_date,$end_date){

$fetch = DB::table('tbl_wallet_transactions')
->whereDate('date_transaction', '>=', $start_date)                                 
->whereDate('date_transaction', '<=', $end_date)                                 
->get();

1
把它改变的诀窍是:
Reservation::whereBetween('reservation_from', [$from, $to])->get();

为了

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

因为在MySQL中,日期必须以字符串类型表示。


1

@masoud,在Laravel中,您需要从表单中请求字段值。因此,

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

在livewire中,有一个微小的变化 -
    Reservation::whereBetween('reservation_from',[$this->from,$this->to])->get();

1

您可以使用DB::raw('')将列转换为MySQL日期格式,并在使用whereBetween函数时进行筛选:

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

1
另一种方法:
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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接