代码之家  ›  专栏  ›  技术社区  ›  Yousef Altaf

Laravel 5.4:选择仅在2天内的记录

  •  1
  • Yousef Altaf  · 技术社区  · 7 年前

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

    我尝试这个

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

    但不起作用,两天前就有记录了 也试试这个

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

    但它也包括了我不想要的今天的记录。

    我该怎么用 carbon DATE

    5 回复  |  直到 7 年前
        1
  •  3
  •   apokryfos    7 年前

    你应该这样做:

    ->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 也可以。

        2
  •  2
  •   Ts8060    7 年前

    请执行以下操作:

    ->whereDate( 'created_at', '>=', Carbon::today()->subDays( 2 ) )
    ->whereDate( 'created_at', '<', Carbon::today() )
    
        3
  •  1
  •   Tarang patel    7 年前

    加上这个,可能对你有用

    ->whereDate( 'created_at', '>', Carbon::today()->subDays( 2 ) )
    ->whereDate( 'created_at', '!=', Carbon::today())
    
        4
  •  0
  •   story ks    7 年前

    尝试 ->WhereDate(“创建时间”、“<”、Carbon::Now()->添加日期(2))

        5
  •  0
  •   H H    7 年前

    你可以使用 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/