如何使用Laravel和Eloquent查询两个日期之间的关系


How to query between two dates using Laravel and Eloquent?

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

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

这在普通SQL中是select * from table where 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子句:whereIn, whereNotIn, whereNull, whereNotNull, whereDate, whereMonth, whereDay, whereYear, whereTime, whereColumn , whereExists, whereRaw

关于Where子句的Laravel文档

我已经创建了模型范围

要了解更多关于scopes的信息,请查看以下链接:

  • laravel.com/docs/eloquent # query-scopes

  • medium.com/@janaksan/using-scope-with-laravel

代码:

   /**
     * Scope a query to only include the last n days records
     *
     * @param  'Illuminate'Database'Eloquent'Builder $query
     * @return 'Illuminate'Database'Eloquent'Builder
     */
    public function scopeWhereDateBetween($query,$fieldName,$fromDate,$todate)
    {
        return $query->whereDate($fieldName,'>=',$fromDate)->whereDate($fieldName,'<=',$todate);
    }

在控制器中,将Carbon Library添加到顶部

use Carbon'Carbon;

获取从现在起最近10天记录

 $lastTenDaysRecord = ModelName::whereDateBetween('created_at',(new Carbon)->subDays(10)->startOfDay()->toDateString(),(new Carbon)->now()->endOfDay()->toDateString() )->get();

获取从现在起最近30天记录

 $lastThirtyDaysRecord = ModelName::whereDateBetween('created_at',(new Carbon)->subDays(30)->startOfDay()->toDateString(),(new Carbon)->now()->endOfDay()->toDateString() )->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();

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

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

下面应该可以工作:

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

如果您需要在日期时间字段应该像这样。

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

试试这个:

既然你是基于单列值抓取,你可以简化你的查询:

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

根据条件检索:laravel docs

希望有帮助。

我遵循了其他贡献者提供的有价值的解决方案,并面临一个没有人解决的小问题。如果reservation_from是一个日期时间列,那么它可能不会产生预期的结果,并且会遗漏日期相同但时间超过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();

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

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

您还需要使用Carbon

use Carbon'Carbon;

这是我的答案是工作谢谢你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();

技巧是改变它:

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

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

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

@masoud,在Laravel中,您必须从表单请求字段值。

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

在livewire中,有一个微小的变化-

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

您可以使用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();

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

之前
$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中传递准确的格式。