首页 > 解决方案 > 有没有更好的方法可以使用碳从 laravel 的当前月份和年份获取 12 个月的基础

问题描述

我有一个如下图所示的图表。

我们应该如何从当前月份获取 12 个月的基础?

这是我使用月份和年份过滤器的完整 12 个月期间的实现。忽略其他变量,只需查看获取月份的过滤器。

/** set and iterate over 12 months period from [1 January] up to [12 December] */
    for ($i = 1; $i <= 12; $i++) {

        $months[$i] = $questionAnswer->withCount(['userAnswers' => function ($userAnswer) use ($i, $companyId) {

            $userAnswer->where('skip', 0)
                ->where('company_id', $companyId)
                ->whereMonth('created_at', $i)
                ->whereYear('created_at', Carbon::now()->year);
        }])->get();
    }

但这只能得到当年的完整 12 个月。我想获得当年最后一个月之前的 12 个月。例如,请查看附件图像并观察最新月份数据之前的月份,在这种情况下是 7 月,无论年份如何。

在此处输入图像描述

这是我提出的算法和正在进行的实现。如果您有更好的方法可以提出,请发布您的答案。

// 1. Get data for the current year and previous year
// 2. Get 12 months base from the current month and year and data from previous `year if month is not yet completed for the current year`
// 3. Use filters for the current month year and previous month year (this is what I'm referring from my code)

标签: phplaravel

解决方案


使用->subMonth()orsubMonths(n)
您可以从 Carbon 日期中减去一个月或月数。
例如

    $n = // no. of months that you can get from a loop;

    $currentDate = now()->subMonths($n);
    $userAnswer->where('skip', 0)
        ->where('company_id', $companyId)
        ->whereMonth('created_at', $currentDate->month)
        ->whereYear('created_at', $currentDate->year);

推荐阅读