Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel查询生成器-如何求和?_Php_Mysql_Laravel_Eloquent - Fatal编程技术网

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

Php Laravel查询生成器-如何求和?,php,mysql,laravel,eloquent,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_d

我为用户记录一年中每个月的时间条目。时间的格式如下: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_月的总和,以便计算每个月的总时间值

这是我的迁移时间

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


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

$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
转换为所需格式

我希望这有帮助

注意:这假设
完成时间不超过记录中指定的
开始日期。

$monthDurations=$user->times()
->年份(2019年开始日)
->挑选(
\DB::raw('SUM(TIME_TO_second(duration))作为'month_duration_in_seconds'),
\DB::raw('DATE'格式(开始日期,%Y-%m)为'year'和'month'),
“类别”,
“用户id”
)
->groupBy(\DB::raw('DATE'格式(开始日期,“%Y-%m”)),'category','user\u id')
->get();

所以您希望示例1月=20日,2月=50日。。。像那样?把你的桌子拿出来我会帮你的没错!在op.Edit中发布了我的表格:我可能应该提到,我想按月份和类别对总数进行分组,但我还没有弄清楚如何按类别对它们进行分组。例如:1月-休假时间:1月50日-加班时间:2月25日-加班时间:25日-但我对每月的总数没问题,我可以算出其余的