Laravel选择5分钟以上的记录? [英] Laravel select records older than 5 minutes?
问题描述
我有Laravel应用,我每隔3秒就会用心跳定期检查一次用户登录(演示目的,实际上是5分钟).对于每个节拍,我都会检查用户在当前时间的上一次活动是否也为5分钟.如果是这样,请将其注销.
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 with current time is also 5 minutes. If it is, log them out.
这是我的代码:
$result = DB::table('db_user')->where('id_user','=',Session::get('id_user'))->where('last_activity','>=',"now() - interval 5 minute")->get();
if(!empty($result))
return Redirect::to('/logout');
else
return Response::json('still-alive');
我的问题是,这不起作用.如果我将操作数更改为<=
,它将在5分钟前立即将我注销,如果操作数是>=
,即使5分钟后它也不会注销我,有人可以解释为什么吗?
My problem is, this doesn't work. If I change the operand to <=
, it will log me out immediately before 5 minutes, if the operand is >=
, even after 5 minutes it won't log me out, can anyone explain why?
-编辑-
感谢所有答案,我通过将代码修改为以下方式解决了我的问题:
Thanks for all the answers, I solved my problems by modifying my code to:
$result = DB::table('db_user')->where('id_user','=',Session::get('id_user'))->first();
if(!empty($result))
if(strtotime($result->last_activity) < strtotime("-5 minutes"))
return Redirect::to('/logout');
else
return Response::json('still-alive');
else
return Response::json('no-record');
推荐答案
假设您的业务逻辑正确,请尝试在where
子句中使用PHP代替SQL字符串:
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();
此外,最好始终输出已执行的SQL查询,以确保Laravel的行为符合预期:
Also, it is a good practice to always output the executed SQL queries just to make sure Laravel behaves as expected:
$queries = DB::getQueryLog();
这篇关于Laravel选择5分钟以上的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!