简体   繁体   English

Laravel 9 子查询目标链接 model where 子句中的列

[英]Laravel 9 sub-query target linked model columns in where clause

I'm working inside a Laravel 9 project and am trying to perform a query and return my Monitor model where the User role of the monitor is a customer (eventually adding more fields).我在 Laravel 9 项目中工作,并试图执行查询并返回我的Monitor model ,其中监视器的User角色是客户(最终添加更多字段)。

My current query attempt throws an error:我当前的查询尝试引发错误:

Property [user] does not exist on the Eloquent builder instance. Eloquent 构建器实例上不存在属性 [用户]。

What am I missing?我错过了什么?

/**
 * Get inactive users
 *
 * @return array
 */
protected function getInactiveUsersWithMonitors()
{
    $monitors = Monitor::with('user')->where(function ($query) {
        $query->user->where('role', 'customer');
    })->get();

    return $monitors;
}

If you have already defined the user function in the Monitor model.如果您已经在Monitor model 中定义了user function。 Here is what you should do.这是你应该做的。

/**
 * Get inactive users
 *
 * @return array
 */
protected function getInactiveUsersWithMonitors()
{
    /* $monitors = Monitor::with('user')->where(function ($query) {
        $query->user->where('role', 'customer');
    })->get(); */

     $monitors = Monitor::whereHas('user', function($query)
{
    $query->where('role', 'customer');

})->get();
    

    return $monitors;
}

This will get all the details from the monitors table as well as the corresponding details from users table.这将从monitors表中获取所有详细信息以及从users表中获取相应的详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM