Laravel select records older than 5 minutes?

前端 未结 3 411
遥遥无期
遥遥无期 2021-02-05 21:58

I have Laravel app where i check user loggedin regularly with a heartbeat for every 3 seconds (demo purpose, actually 5 minutes). For each beat I check if user\'s last activity

相关标签:
3条回答
  • 2021-02-05 22:23

    You can use whereRaw():

    $result = DB::table('db_user')->where('id_user','=',Session::get('id_user'))->whereRaw('last_activity >= now() - interval 5 minute')->get();
    

    or

    $result = DB::table('db_user')->where('id_user','=',Session::get('id_user'))->whereRaw('last_activity >= now() - interval ? minute', [5])->get();
    
    0 讨论(0)
  • 2021-02-05 22:37

    Assuming your business logic is correct, try using PHP instead of an SQL string in the where clause:

    $date = new DateTime;
    $date->modify('-5 minutes');
    $formatted_date = $date->format('Y-m-d H:i:s');
    
    $result = DB::table('db_user')->where('id_user','=',Session::get('id_user'))->where('last_activity','>=',$formatted_date)->get();
    

    Also, it is a good practice to always output the executed SQL queries just to make sure Laravel behaves as expected:

    $queries = DB::getQueryLog();
    
    0 讨论(0)
  • 2021-02-05 22:41

    The accepted answer is correct, but you could make it even cleaner by using a query scope on the User model (assuming that you have a User model)...

    $result = User::currentUser()->activityOlderThan(self::HEARTBEAT_INTERVAL)->get();
    

    Your User model would then have these functions:

    public function scopeCurrentUser($query)
    {
        return $query->where('id_user', '=', Session::get('id_user'));
    }
    

    And

    public function scopeActivityOlderThan($query, $interval)
    {
        return $query->where('last_activity', '>=', Carbon::now()->subMinutes($interval)->toDateTimeString());
    }
    

    Now your code is clean and easy to read :-)

    0 讨论(0)
提交回复
热议问题