Laravel 7 Eloquent 模型 -(无法在 table 之外的地方做)无法在 businessDeveloper.user_id、select * 上找到专栏

Laravel 7 Eloquent models - (not being able to do where outside table) Unable to find column on businessDeveloper.user_id, select * from opportunities

SQLSTATE[42S22]:未找到列:1054 'where clause' 中的未知列 'businessDeveloper.user_id'(SQL:select * 来自 opportunities 其中 businessDeveloper.user_id = 3)

您好,我正在为一个学校项目使用 Laravel 7 和 eloquent 模型。我们被告知不要使用连接,除了使用格式化数据制作自定义 JSON 字符串外,这将需要大量工作,因为我对其他功能也有同样的问题。我不知道如何解决我的问题。表格是这样的: 机会(business_developer_id FK) belongTo-> businessDevelopers(user_id FK) belongTo-> 用户 因此,我尝试为登录的业务开发人员展示所有机会。但这似乎不起作用:

public function qryOpportunities()
    {
        $opportunities = Opportunity::where('businessDeveloper.user_id', Auth::id())->with('businessDeveloper.user', 'consultantOpportunity.consultant.user', 'contactPerson', 'customer', 'headOfDepartment.user')->get();
        return $opportunities;
    }

非常感谢能够显示登录业务开发人员的所有机会的解决方案。提前致谢。

尝试 ->whereHas() :

public function qryOpportunities()
{
    $opportunities = Opportunity::whereHas('businessDeveloper', function($q) {
        $q->where('user_id', Auth::id());
    })
    ->with('businessDeveloper.user', 'consultantOpportunity.consultant.user', 'contactPerson', 'customer', 'headOfDepartment.user')
    ->get();
    return $opportunities;
}

您可以在此处查看 whereHas() 的文档:https://laravel.com/docs/7.x/eloquent-relationships#querying-relationship-existence

我建议你使用这个代码:

public function qryOpportunities()
{
    return Opportunity::query()
        ->whereHas('businessDeveloper', function($query) {
        $query->where('user_id', Auth::id());
    })->with('businessDeveloper.user', 'consultantOpportunity.consultant.user', 'contactPerson', 'customer', 'headOfDepartment.user')
      ->get();
}