php - Laravel 查询生成器 - 如何求和?

标签 php mysql laravel eloquent

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

示例:08:32:00

以下是我将月份分组的方式:

  $data = $user->times()->whereYear('start_day', 2019)->get();
        $group_months = $data->groupBy(function($entry) {
             return Carbon::parse($entry->start_day)->format('m');
      });

如何对 $group_months 进行求和,以便获得每个月的总时间值?

这是我的多次迁移

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

关于php - Laravel 查询生成器 - 如何求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58433283/

相关文章:

php - laravel 从数据库读取数据返回重复结果

php - 如何生成动态加载数据库的所有可能结果?

php - Laravel 5.1 - 每次刷新都会重新生成 session

mysql - 根据用户的技能以及 Laravel 查询生成器中的匹配技能来选择用户

php - 路由器控制 CSS 和图像

php - 具有多个输入的多文件上传

JavaScript 将字符串和整数从 PHP 传递到函数中

php - 如何从循环停止的地方读取?

php - 如何从 Laravel 返回的数组中获取键的值

php - 创建将从 url 中提取图像名称的 javascript RegEx