Laravel 5.4:选择仅两天内的记录

时间:2018-07-24 08:36:58

标签: laravel date php-carbon

例如,我只需要提取两天内的所有记录 今天是24/7,所以我需要23/7和22/7中的所有记录

我尝试

->whereRaw('DATE(created_at) = DATE_SUB(CURDATE(), INTERVAL 2 DAY)')

但无法正常工作,它将获取两天前的记录 也可以尝试

->whereDate( 'created_at', '>', Carbon::now()->subDays( 2 ) )

但是它包含了我今天也不需要的记录。

我该如何使用carbonDATE

5 个答案:

答案 0 :(得分:3)

您应该这样做:

->whereDate('created_at', '>', Carbon::today()->subDays( 2 ))
->whereDate('created_at', '!=', Carbon::today());

今天将不包括在内。

如果您希望更多原始查询,则可以执行以下操作:

->whereBetween(\DB::raw("DATE(`created_at`)"), [ Carbon::today()->subDays(2), Carbon::today()->subDays(1) ]);

注意:今天使用它是因为它使代码看起来更具表现力,但是now也可以使用。

答案 1 :(得分:2)

执行以下操作:

->whereDate( 'created_at', '>=', Carbon::today()->subDays( 2 ) )
->whereDate( 'created_at', '<', Carbon::today() )

答案 2 :(得分:1)

添加此内容,可能对您有用

->whereDate( 'created_at', '>', Carbon::today()->subDays( 2 ) )
->whereDate( 'created_at', '!=', Carbon::today())

答案 3 :(得分:0)

尝试    -> whereDate('created_at','<',Carbon :: now()-> addDays(2))

答案 4 :(得分:0)

您可以使用whereBetween https://laravel.com/docs/5.6/queries#where-clauses

->whereBetween('created_at', [now()->subDays(2)->startOfDay(), now()->endOfDay()]) 

-

您还可以使用多个where子句:

->where('created_at', '>', now()->subDays(2)->startOfDay())
->where('created_at', '<', now()->endOfDay())

-

您也可以使用whereDate

->whereDate('created_at', '>', now()->subDays(2)->startOfDay())
->whereDate('created_at', '<', now()->endOfDay())

-

碳文档: https://carbon.nesbot.com/docs/

相关问题