Laravel查询生成器-如何求和? [英] Laravel Query Builder - How can I sum?

查看:75
本文介绍了Laravel查询生成器-如何求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在记录用户每年一年中每个月的时间条目.时间采用以下格式:hh:mm:ss

I'm logging time entries for users for each month of the year. The times are in the following format: hh:mm:ss

示例:08:32:00

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

我如何求和$ group_months,这样我就可以得出每个月的总时间值?

How can I sum $group_months, so I can the total time value for each month?

这是我的迁徙时间

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

推荐答案

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

这篇关于Laravel查询生成器-如何求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆