php - 有没有更好的方法可以使用碳从 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)
解决方案
使用->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);
推荐阅读
- elasticsearch - ElastAlert 将查询和范围组合成 OR 子句
- node.js - 如何注销并清除 Passport 和 Express-session 的会话?
- jenkins - Conan Artifactory Jenkins 集成失败
- pandas - 计算 Pandas 中距离最近日期的剩余天数
- github - 无法在 r markdown 中打开 githubu 文档中的代码跟踪
- c++ - 将对象移动到向量对字符串c ++的前面
- xslt - 如何删除重复条目 - XSLT
- r - 用户上传文件时的R ggplot
- php - Laravel 每个用户只有一个friend_id
- c# - 如何以自定义格式 dd/MM/yyyy 在 SQL Server 数据库中插入 Datetimepicker 值