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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 14:15:30