[英]How can I do this query with Laravel Eluquent Query Builder
[英]Laravel Query Builder - How can I sum?
我正在为一年中的每个月记录用户的时间条目。 时间格式如下: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');
这尚未经过测试。 但是,您应该能够通过以下方式实现此目的:
$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
转换为所需的格式。
我希望这有帮助。
注意:这假设完成时间不超过记录中指定的开始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.