Help us understand the problem. What is going on with this article?

Laravel で MySQLのTime型の最大値を超えて集計する

やりたいこと

MySQLのTime型は

'-838:59:59' から '838:59:59'
にまでしか対応していません。

なので仮にDBに○○した時間をtime型で保存し、合計を取り出そうとすると上限に当たる可能性がありませす

集計方法

MySQLのTime_TO_SEC関数を使います。
その名の通りこれは、Timeを秒数に直してくれます。
秒数に直したものを合計し、それを取得します。

取得した秒数をPHPでHH:MMに整形してあげれば、上限を超えた状態になります。

TestController.php
public function summary()
{
    $user = User::selectRaw('SUM(TIME_TO_SEC('sleep_time')) as total_sleep_time')
      ->where('name','太郎')
      ->first();

    $time = $user->total_sleep_time;
    // HH:MM
    sprintf('%02d:%02d', ($time / 3600),($time / 60 % 60))
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away