首页 > 解决方案 > 如何在 laravel 中获取最近 30 天的数据?

问题描述

我正在查询过去 30 天的数据,但没有得到预期的结果。今天是 2021 年 1 月 18 日,最后三天的日期是 2021 年 1 月 18 日,但我只得到这个月份和年份的数据,而不是 12 月我怎么能得到?我的代码是

$startDate = \Carbon\Carbon::now()->subDays(30);
$endDate = \Carbon\Carbon::now();
    return Auth::user()->invoices()
        ->whereBetween("invoice_date", [$startDate, $endDate])
        ->orderBy('created_at', 'DESC')
        ->get();

并尝试其他类似的解决方案,

$date = \Carbon\Carbon::now()->subDays(30);
    return Auth::user()->invoices()
        ->whereDate("invoice_date", '>=', $date)
        ->orderBy('created_at', 'DESC')
        ->get();

得到相同的输出我的数据库表数据是,

在此处输入图像描述

并显示出来是

在此处输入图像描述

标签: laraveleloquent

解决方案


试试下面的代码,它会帮助你:

$date = \Carbon\Carbon::now()->subDays(30);
$year = \Carbon\Carbon::now()->year;

return Auth::user()->invoices()
    ->where("invoice_date", '>=', $date)
    ->where("invoice_date", '>=', $year)
    ->orderBy('created_at', 'DESC')
    ->get();

推荐阅读