How to get the average time in Laravel

删除回忆录丶 提交于 2021-02-08 08:55:19

问题


I want get the the average time between start-time and end-time and Where CUR-Time GroupBY user-name i written the sql in laravel it's showing some error i can't find what's that because i'm new to that laravel please help to fix this sql error i submit the my sql and the error message.

 $avagTime = DB::table( 'active_user' )
            ->select(DB::raw('AVG(TIME_TO_SEC(acu_et) - TIME_TO_SEC(acu_at))'))
            ->where (DATE('acu_at') == ('CURDATE()'))
            ->get();[![enter image description here][1]][1]


回答1:


Try this code:

$currentTime = Carbon::now()->toDateTimeString();

$avagTime = DB::table( 'active_user' )
          ->select(DB::raw('AVG(TIME_TO_SEC(acu_et) - TIME_TO_SEC(acu_at))'))
          ->where ('acu_at', $currentTime)
          ->get();

I think it would be helful. Thanks




回答2:


Isn't it better to take the logic out of there? I prefer to just fetch date times from DB and using Carbon to convert them to Unix timestamp. Then use them as they are simple int.




回答3:


The issue is in your where clause. Laravel's query builder has a whereDate() method that would be perfect fo this:

$avagTime = DB::table('active_user')
    ->selectRaw('AVG(TIME_TO_SEC(acu_et) - TIME_TO_SEC(acu_at))')
    ->whereDate('acu_at', today())
    ->get();

NB If you wanted to pass the where cause as a raw query like you have in your example you would need to use something like whereRaw() instead or where().



来源:https://stackoverflow.com/questions/54838709/how-to-get-the-average-time-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!