替代laravel whereHas方法

LARAVEL-Builder#

这是一个可以提升 Laravel ORM 关联关系查询性能的扩展包,

环境#

  • PHP >= 7

  • laravel >= 5.5

安装#

gitee 地址

gitee.com/yjshop/laravel-builder.g...

composer require eugenes/laravel-builder

简介#

Laravel 的关联关系查询 whereHas 在日常开发中给我们带来了极大的便利,但是在主表数据量比较多的时候会有比较严重的性能问题,主要是因为 whereHas 用了 where exists (select * ...)

这种方式去查询关联数据。

通过这个扩展包提供的 whereHasIn,whereHasJoin 方法

方法#

whereHasIn#


App(CompanyStaffModel::class)->whereHasIn('section', function ($query) {

 $query->where('id', 1);

})->first();

SELECT *

FROM  `lk_company_staff`

WHERE  `lk_company_staff`.`id`  IN (SELECT  `lk_company_staff_section_relation`.`userid`

 FROM  `lk_company_staff_section_relation`

 WHERE  `lk_company_staff`.`id` = `lk_company_staff_section_relation`.`userid`

 AND  `id` = 1) LIMIT  1

whereHasJoin#


App(CompanyStaffModel::class)->yjselect('*')->whereHasJoin('section', function ($query) {

         $query->yjwhere('id', 1);

})->first();

select  `lk_company_staff`.*

from  `lk_company_staff`

         left join  `lk_company_staff_section_relation`

                   on  `lk_company_staff_section_relation`.`userid` = `lk_company_staff`.`id`

where ((`lk_company_staff_section_relation`.`id` = 1)) limit  1

yjwhere#


App(CompanyStaffModel::class)->yjwhere('id', 1)->first();

select *

from  `lk_company_staff`

where  `lk_company_staff`.`id` = 1  limit  1

yjselect#


App(CompanyStaffModel::class)->yjselect('id')->first();

select  `lk_company_staff`.`id`

from  `lk_company_staff`  limit  1

yjsum#

yjpluck#

yjorderBy#

yjorderByDesc#

orWhereHasIn#

orWhereHasNotIn#

whereHasMorphIn#

orWhereHasMorphIn#

License#

The MIT License (MIT).

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。