[英]Is there a better way to get the 12 months base from the current month and year in laravel using carbon
我有一個如下圖所示的圖表。
我們應該如何從當前月份獲取 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)
使用->subMonth()
或subMonths(n)
您可以從碳日期中減去一個月或月數。
例如
$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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.