我正在记录用户时间条目。我的时代迁移如下所示:
Schema::create('times', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->date('start_day');
$table->text('category');
$table->time('start_time');
$table->time('finish_time');
$table->time('duration');
$table->text('notes');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
注意:持续时间计算start_time和finish_time之间的总差
额我使用以下代码将月份和类别分组在一起:
$data = $user->times()->whereYear('start_day', 2019)->get();
$group_months = $data->groupBy(function($entry) {
return $entry->category;
})->map(function($items) {
return $items->groupBy(function($entry) {
return Carbon::parse($entry->start_day)->format('m');
})
->map(function($items) {
return $items->count();
});
});
如果我运行 dd($group_months(,我会得到这个:
Collection {#322 ▼
#items: array:1 [▼
"Comp Time Used" => Collection {#318 ▼
#items: array:1 [▼
10 => 2
]
}
]
}
如您所见,它按类别和月份对其进行分组,并计算条目总数。
我现在想获取每个月的总持续时间及其相应的类别。
因此,例如,如果我们引用上面的集合,我有:2 10 月的时间条目在使用的补偿时间下。
假设时间条目 1 持续时间 = 12:00:00,时间条目 2 持续时间 = 05:00:00
我希望总持续时间显示:17:00:00。我该怎么做?
我更正并检查了我之前的答案。
$monthDurations = $user->times()
->whereYear('start_day', 2019)
->select(
DB::raw('TIME_FORMAT(SUM(TIME_TO_SEC(duration)), "%H:%i:%s") as `month_duration`'),
DB::raw('DATE_FORMAT(start_day, "%Y-%m") as `year_month`'),
'category',
'user_id'
)
->groupBy(DB::raw('DATE_FORMAT(start_day, "%Y-%m")'), 'category', 'user_id')
->get();