【问题标题】:How to sort grouped objects primarily by year and secondarily by month from timestamp?如何从时间戳中主要按年份和其次按月份对分组对象进行排序?
【发布时间】:2019-02-07 13:25:54
【问题描述】:

我有几个从 Invoice 类实例化的对象。

每个都有属性sorting_date(时间戳)。

我想按年份和月份对所有发票进行分组,并在列表中显示月份,最新的在前,其余的按时间顺序排列。从最新到最旧。

我想要什么:

2019 年 2 月
2019-1月
2018-12月

我有什么:

2019 年 1 月
2018-12月
2019-2月

我的代码:

$months = Invoice::where("user_id", $id)->pluck('sorting_date')->groupBy('month', 'year');
$months = $months->sortBy('year');

在 tinker $months 经过上述操作后看起来是这样的(只有几个月作为键):

Illuminate\Support\Collection {#3069
     all: [
       1 => Illuminate\Support\Collection {#3066
         all: [
           Illuminate\Support\Carbon @1546796483 {#3052
             date: 2019-01-06 17:41:23.0 UTC (+00:00),
           },
         ],
       },
       12 => Illuminate\Support\Collection {#3043
         all: [
           1 => Illuminate\Support\Carbon @1544118083 {#3060
             date: 2018-12-06 17:41:23.0 UTC (+00:00),
           },
         ],
       },
       2 => Illuminate\Support\Collection {#3040
         all: [
           2 => Illuminate\Support\Carbon @1549474883 {#3058
             date: 2019-02-06 17:41:23.0 UTC (+00:00),
           },
           3 => Illuminate\Support\Carbon @1549474883 {#3033
             date: 2019-02-06 17:41:23.0 UTC (+00:00),
           },
         ],
       },
     ],
   }

我了解我的代码不起作用。我在 sortBy('year') 中写什么并不重要。我什至可以写 sortBy('banana') 并给出相同的结果。它不会给出错误,但也不会给出预期的结果。即使这样做了,它也只会按年份对它们进行排序。在那一年内,月份仍然可能是错误的。

【问题讨论】:

  • 我认为您需要在采摘之前进行排序。因为 pluck 只会保留键 sorting_date,所以不能按不存在的键排序。
  • 你想达到什么目的?是否要统计每个月的发票数量并按日期降序排列?
  • @VincentDecaux 但是在排序日期中我需要的所有信息都存在吗?因为它是一个完整的时间戳。
  • @Mozammil 正如问题所述,我想列出所有具有该月份时间戳的发票的月份。该列表还应按年份排序,例如 2018 年 1 月和 2019 年 1 月应该是不同的列表项。

标签: php laravel php-carbon


【解决方案1】:

您可以在 SQL 中完成所有这些操作。您不必使用 Collections 来操作您的结果集。

因此,使用查询生成器(或 Eloquent),您可以执行以下操作:

return DB::table('invoices')
    ->selectRaw('YEAR(sorting_date) AS year, MONTHNAME(sorting_date) month, COUNT(*)')
    ->groupby('year','month')
    ->orderBy('year', 'desc')
    ->orderByRaw('MONTH(sorting_date) DESC')
    ->get();

这是一个example,您也可以使用它。

【讨论】:

    猜你喜欢
    • 2012-01-11
    • 2014-05-31
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多