Laravel Eloquent关联查询异常缓慢,MySQL原生却很快的问题排查
为何我的Laravel Eloquent查询运行异常缓慢?
我在Laravel任务中执行的一个查询速度极不稳定,相同的查询有时需1-2分钟才能返回结果,有时仅需1-2秒。
慢完整Eloquent查询(需1-2分钟完成)
$relevantRobot = App\Robot::where('serial_number', 'TEST-ID') ->whereHas('robot_maps', function($query) use ($robot_map_name) { $query->where('name', $robot_map_name); }) ->with(['robot_maps' => function($query) use ($robot_map_name) { $query->where('name', $robot_map_name); }, 'current_robot_position', 'current_robot_position.robot_map', 'latest_robot_deployment_information_request' ]) ->first();
精简后慢Eloquent查询(需1-2分钟完成)
$relevantRobot = App\Robot::where('serial_number', 'TEST-ID') ->whereHas('robot_maps', function($query) use ($robot_map_name) { $query->where('name', $robot_map_name); }) ->with('current_robot_position') ->first();
精简后快Eloquent查询(不到1秒完成)
$relevantRobot = App\Robot::where('serial_number', 'TEST-ID') ->whereHas('robot_maps', function($query) use ($robot_map_name) { $query->where('name', $robot_map_name); }) ->with('latest_robot_deployment_information_request') ->first();
原生SQL查询(不到1秒完成)
select * from `robots` where `serial_number` = 'TEST-ID' and exists (select * from `robot_maps` where `robots`.`id` = `robot_maps`.`robot_id` and `name` = 'test' and `active` = 1);
Eloquent关联定义
public function current_robot_position(){ return $this->hasOne('App\RobotMapPositionLog','robot_id','id') ->orderBy('id','desc'); }
已尝试的解决方法
- 发现预加载
current_robot_position导致查询变慢后,为该关联使用的id字段添加索引,性能未得到提升 - 通过
toSql()将Eloquent查询转换为原生MySQL查询,执行速度极快(不到1秒) - 后续更新:已确定
->with('current_robot_position')是整个查询变慢的原因,为外键列robot_id添加索引,将orderBy('id','desc')替换为latest(),但均未显著缩短加载时间
疑问
哪里出错了?我遗漏了什么?
内容的提问来源于stack exchange,提问作者Yeo Bryan
相关产品推荐
相关产品推荐

