whereHas 有缺陷,会把主表全都遍历一遍
如何在使用eloquent查询的前提下,还能实现join的效果(目的是join后用关联表的字段作为条件查询)?
而不是whereHas最终转化出来的where exists 效果,真是效率太低了。
explain select count(*) from `user` where exists (select * from `recommendation` where `user`.`id` = `recommendation`.`user_id` and `from_id` = '1');
explain select count(*) from user u join recommendation r on u.id = r.user_id where r.from_id = 1;
举例如上,第一条sql是whereHas生成的,会把主表user表完全扫一遍,一个很简单的任务,执行了几十秒,php都超时了。
而下面一条join,自己写的,一样的效果,瞬间就能跑完。
无奈的是,该路由下的功能已经全部用eloquent做的数据查询了,现在想改Query Builder也来不及了。除非下定决心重构。
请问怎么才能在eloquent中使用join查询?
跪谢!
不知道这个可不可以帮你
给 Eloquent 的 whereHas 加个 where in 的优化