【问题标题】:Laravel Query Builder - How can I sum?Laravel 查询生成器 - 我如何求和?
【发布时间】:2019-10-17 13:00:14
【问题描述】:

我正在为一年中每个月的用户记录时间条目。时间格式如下: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');

【问题讨论】:

  • 所以你想要示例 1 月 = 20,2 月 = 50 ......这样吗?显示你的桌子我会帮助你
  • 没错!把我的桌子贴在 op。编辑:我可能应该提到,我想按月份和类别对总数进行分组,但我还没有弄清楚如何按类别对它们进行分组。例如:1 月 - 假期时间:1 月 50 日 - 加班时间:2 月 25 日 - 加班时间:25 但我对每月总数很好,我可以计算出其余的

标签: php mysql laravel eloquent


【解决方案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】:

    这还没有经过测试。但是,您应该能够通过以下方式实现此目的:

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

    对月份进行分组后,您可以使用->map()收集方法获取该月份内时间到达的秒差。

    然后您可以使用->sum() 将所有内容加起来。

    最后你可以使用gmdate()$seconds 转换为所需的格式。

    我希望这会有所帮助。

    注意:这假设finish_time 不超过记录中指定的start_day

    【讨论】:

      猜你喜欢
      • 2019-09-12
      • 2021-11-13
      • 2015-12-03
      • 2015-12-13
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      • 2021-09-12
      相关资源
      最近更新 更多