Laravel Query Builder - How can I sum?

我们两清 提交于 2019-12-11 16:39:16

问题


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');


回答1:


$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();



回答2:


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.



来源:https://stackoverflow.com/questions/58433283/laravel-query-builder-how-can-i-sum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!