【问题标题】:Laravel groupBy using Carbon - unexpectedly limiting grouped array lengthLaravel groupBy using Carbon - 意外限制分组数组长度
【发布时间】:2017-07-18 12:02:05
【问题描述】:
    $results = Result::orderBy("created_at", "asc")
    ->whereBetween('created_at', array($from, $to))
    ->get()
    ->groupBy(function($date) use($interval) {
        return Carbon::parse($date->created_at)->format($interval);
    });

我正在尝试根据用户在前端选择的内容将结果集分组为天/周/月。

以上方法可以分组返回结果,但它增加了一个奇怪的限制。

假设我的$from/$to 跨度为 2 年。

如果$interval 是“d”,那么它只返回 31 个组(一个月 31 天)。所以它应该只返回前 31 天作为组。

如果$interval 是“W”,那么它只返回 52 个组(一年中的 52 周)。所以它应该只返回前 52 周作为组。

如果$interval 是“m”,那么它只返回 12 个组(一年中的 12 个月)。所以它应该只返回前 12 个月作为组。

我找不到任何解释为什么它对分组结果的数量实施这些限制。很多人似乎都在使用这种方法按日期分组,但我找不到其他人引用相同的问题。

【问题讨论】:

  • 那么问题是 12 个月组没有两年的结果,还是您期望 24 个月组代替?
  • 我预计会有 24 个组,但它限制为 12 个。

标签: php mysql laravel eloquent php-carbon


【解决方案1】:

您需要先按 X 分组,然后按年份分组,否则您会将这两年的值放在同一个存储桶中。

例如,如果您按月分组,您最终会得到 2017 年 1 月的值和 2016 年 1 月的值,因为它们都匹配相同的格式“M=01”。

$results = Result::orderBy("created_at", "asc")
->whereBetween('created_at', array($from, $to))
->get()
->groupBy(function($date) use($interval) {
    return Carbon::parse($date->created_at)->format("Y ".$interval);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 2014-08-19
    • 2018-03-21
    • 2017-01-22
    • 1970-01-01
    • 2012-04-27
    相关资源
    最近更新 更多