Laravel RAW查询添加多列浮点值

I'm storing value into database like 9:30 and 1 (my datatype is float in database for this column), when i'm retrieving i cant able to add two numbers , it is printing like 10 but it must be in 10:30 , i'm using laravel to add these two column

     $get=DB::table('table_name')->select(DB::raw('sum(hours) AS hours'))
                                 ->get();

can anyone please solve my issue ??

The best thing to do is to change the datatype from float to integer. Generally in most programming and database level, float value is problematic and could also lead to precision issues/problems.

So my proposal is:

  • Store the time in minutes (or the least unit based on your situation)
  • Retrieve it, and divide it by 60 then you have the right value without employing hacky and unstable ways to resolve it.

I hope this is useful.

float is for numbers with comma , . What you want to save a clock time with :.

So you could convert your time to float before storing it to the database, 10:30 -> 10.5 and then sum it up like

$get=DB::table('table_name')->select(DB::raw('sum(hours) AS hours'))
                             ->first();
$hours = str_replace('.', ':', $get->hours);

This solution isn't the beast because there are better approaches to deal with dates by saving them as a date object and not as a float one.

Another approach is to use smalldatetime instead of float to save the value. Then you save times and not numbers with that you can work.

You can do so after retrieving your data from db

$n1 = '9:30';
$timestamp = strtotime($n1);
echo date('H:i',strtotime('+1 hour',$timestamp));