[英]Laravel Query Builder - How can I sum?
I'm logging time entries for users for each month of the year.我正在为一年中的每个月记录用户的时间条目。 The times are in the following format: hh:mm:ss
时间格式如下:hh:mm:ss
example: 08:32:00示例: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?我怎样才能总结 $group_months,所以我可以得到每个月的总时间值?
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');
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.对月份进行分组后,您可以使用
->map()
收集方法来获取月份内时间到达的秒数差异。
You can then add the all up using ->sum()
.然后,您可以使用
->sum()
将所有内容加起来。
Finally you can use gmdate()
to convert $seconds
to the required format.最后,您可以使用
gmdate()
将$seconds
转换为所需的格式。
I hope this helps.我希望这有帮助。
Note: This assumes that the finish_time
does not go past the start_day
specified on the record.注意:这假设完成时间不超过记录中指定的开始
start_day
finish_time
。
$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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.