Laravel -如何使用集合对表中的日期字符串进行分组

ztmd8pv5  于 2022-12-05  发布在  其他
关注(0)|答案(1)|浏览(121)

我想分组我的日期,但我不知道如何做到这一点。我尝试使用groupBy(),但它给我一个错误

$user = Auth::user()->id;
$date = productSold::where('user_id',$user)->get();

$collect = collect($date)->map(function ($date) {
    return date('M',strtotime($date->created_at))->groupBy('created_at');
});
return $collect;

错误:对字符串调用成员函数groupBy()
如果不使用groupby,则输出如下:

[
"Oct",
"Oct",
"Nov",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec"
]

我想对"Oct", "Nov", "Dec"进行分组

06odsfpq

06odsfpq1#

它的错误是因为你从一个字符串中按它分组。所以你应该从map函数中取出groupBy语句。所以结果应该是这样的:

$collect = collect($date)->map(function ($date) {
        return [
            "created_at" => date('M',strtotime($date->created_at))
        ];
    })->groupBy('created_at');

结果应该类似于this

相关问题