Laravel 8- Eloquent order table 结果天数组

Laravel 8- Eloquent order table results in days array

我正在尝试 assemble 每个 user/day 的任务图表,但我找不到如何轻松地对其进行排序。

我进行以下查询来收集任务;

$tasksLastMonth = Task::where('user_id', Auth::user()->id)
                        ->whereMonth('date', Carbon::now()->month)
                        ->with('client')->get();

$tasksLastWeek = Task::where('user_id', Auth::user()->id)
                        ->where('date', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])
                        ->with('client')->get();

另一方面,我有两个数组,其中包含星期几和图表 X 轴的月份(有 2 个图表,一个用于一周,另一个用于月份)

$weekDays // [7,8,9,10,11,12,13]
$week // [1,2,3,4,.....,28]

现在,对于 Y 轴,我需要两个长度与星期几和月份相同的数组,其中包含每天的任务数。例如,如果在第 8 天有 5 个任务,它将看起来像这样:

$tasksInWeek = [0,5,0,0,0,0,0];

我还需要其他数组来表示每天的客户数量,但只是不同的数组。如果有一天同一个客户有2个任务,那一天我只需要添加1个客户。

我可能只用查询就可以做到,但我找不到办法。

这应该有效:

$groupedTasks = Task::where('user_id', Auth::user()->id)
            ->whereMonth('date', Carbon::now()->month)
            ->with('client')
            ->get()
            ->groupBy(function ($item) {
              return $item->date->format('Y-m-d');
            })
            ->map(function ($items, $date) {
              return $items->unique('user_id');
            });

这里的想法是,首先,按日期对元素进行分组(而不是使用整数),然后在每个组中只保留不同的用户。

您可以复制几乎相同的逻辑来获取每周图表的数据。