![](/img/trans.png)
[英]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.