前言
前几天在QQ群里看到有位同学请人帮忙根据社区里的文章(给 Eloquent 的 whereHas 加个 where in 的优化)给Eloquent的whereHas方法进行性能优化,因为这篇文章里面提供的代码还是有些细节问题,并不能支持所有的关联关系,所以我抽空写了这个扩展包,支持了所有关联关系。并且我也做了一些小测试,发现在数据量大的情况下优化过后的性能提升非常惊人,下面是一个简单的测试,如果有不正确之处欢迎大家拍砖指正:
主表test_users写入130002条数据,关联表test_user_profiles写入1002条数据,查询代码如下
<?php
/**
* 未优化sql
*
* select * from `test_users` where exists
* (
* select * from `test_user_profiles`
* where `test_users`.`id` = `test_user_profiles`.`user_id`
* )
* limit 10
*/
$users1 = User::whereHas('profile')->limit(10)->get();
/**
* 优化后的sql
*
* select * from `test_users` where `test_users`.`id` in
* (
* select `test_user_profiles`.`user_id` from `test_user_profiles`
* where `test_users`.`id` = `test_user_profiles`.`user_id`
* )
* limit 10
*/
$users1 = User::whereHasIn('profile')-<

本文介绍了如何通过Laravel扩展包提升ORM关联关系查询性能,特别是`whereHasIn`和`whereHasMorphIn`方法,以替代`whereHas`配合`where id in`的查询方式。文中提供了性能测试结果,展示在大量数据下优化后的显著提升,并给出了安装和使用示例。
&spm=1001.2101.3001.5002&articleId=107173435&d=1&t=3&u=f9d3ad960ce24eb88445647ca96209cb)
924

被折叠的 条评论
为什么被折叠?



