I'm logging time entries for users for each month of the year. The times are in the following format: hh:mm:ss
example: 08:32:00
Here's how i'm grouping my months together:
$data = $user->times()->whereYear('start_day', 2019)->get();
$group_months = $data->groupBy(function($entry) {
return Carbon::parse($entry->start_day)->format('m');
});
How can I sum $group_months, so I can the total time value for each month?
Here's my migration for times
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');
This has not been tested. However you should be able to achieve this with the following:
$data = $user->times()
->whereYear('start_day', 2019)
->get()
->groupBy(function($entry) {
return Carbon::parse($entry->start_day)->format('m');
})->map(function ($times, $month) {
$seconds = $times->map(function ($time, $key) {
return \Carbon::parse($time->start_time)->diffInSeconds(\Carbon::parse($time->finish_time));
})->sum();
return gmdate('H:i:s', $seconds);
})->all();
After grouping the month, you can use the ->map()
collection method to get the difference in seconds for reach of the times within the month.
You can then add the all up using ->sum()
.
Finally you can use gmdate()
to convert $seconds
to the required format.
I hope this helps.
Note: This assumes that the finish_time
does not go past the start_day
specified on the record.
$monthDurations = $user->times() ->whereYear('start_day', 2019) ->select( \DB::raw('SUM(TIME_TO_SEC(duration)) as `month_duration_in_seconds`'), \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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.