You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Eloquent关联查询冗余条件处理:多余IS NOT NULL优化方案

问题:Laravel关联查询冗余的company_id is not null条件导致性能下降

直接查询Contact模型时,代码如下:

Contact::where('company_id', auth()->user()->company_id)->get()

生成的SQL为:

select * from "contacts" where "company_id" = 'xxx'

但通过Company与Contact的关联关系查询时:

auth()->user()->company->contacts

生成的SQL会多出一条冗余条件,影响查询性能:

select * from "contacts" where "contacts"."company_id" = 'xxx' and "contacts"."company_id" is not null

已知company_id字段已建立索引,需要在保留关联写法的前提下消除该冗余条件。


解决方案:修改关联定义,移除默认非空约束

在Company模型的contacts关联方法中,通过whereNotNull(false)显式关闭Laravel自动添加的非空条件:

// app/Models/Company.php
public function contacts()
{
    return $this->hasMany(Contact::class)->whereNotNull(false);
}

原理说明

Laravel的hasMany关联默认会为外键添加whereNotNull约束,用于排除外键为null的记录。但如果你的contacts表中company_id字段已经设置了NOT NULL数据库约束,这个条件完全冗余,关闭它后不会影响数据正确性,还能让数据库优化器更高效地利用索引。


内容的提问来源于stack exchange,提问作者Alper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 23:34:56