Laravel 9关联模型字段用于WHERE子句查询报错排查
Laravel 9关联查询错误解决:Property [user] does not exist on the Eloquent builder instance.
问题描述
在Laravel 9项目中,尝试查询并返回关联User角色为customer的Monitor模型时,抛出错误:"Property [user] does not exist on the Eloquent builder instance."
错误代码示例
/** * Get inactive users * * @return array */ protected function getInactiveUsersWithMonitors() { $monitors = Monitor::with('user')->where(function ($query) { $query->user->where('role', 'customer'); })->get(); return $monitors; }
问题原因
闭包内的$query是Eloquent Builder实例,并非Monitor模型实例,无法直接通过->user访问关联关系。要筛选关联模型的条件,需要使用whereHas方法来针对关联模型添加查询约束。
修正后的代码
/** * Get inactive users * * @return \Illuminate\Database\Eloquent\Collection */ protected function getInactiveUsersWithMonitors() { $monitors = Monitor::with('user') ->whereHas('user', function ($query) { $query->where('role', 'customer'); }) ->get(); return $monitors; }
说明
with('user'):预加载User关联,避免后续访问用户数据时出现N+1查询问题whereHas('user', ...):仅筛选出存在关联User且该用户角色为customer的Monitor记录
内容的提问来源于stack exchange,提问作者Ryan H
相关产品推荐
相关产品推荐

