Eloquent 中忽略了 whereHas 中的 where 子句

Jon*_*han 1 laravel eloquent

我尝试使用whereHas和 eloquent进行查询。查询是这样的:

$projects = Project::whereHas('investments', function($q) {
                $q->where('status','=','paid');
            })
            ->with('investments')
            ->get();
Run Code Online (Sandbox Code Playgroud)

我使用 Laravel 5.2 并使用 Postgres 驱动程序。

项目模型为:

public function investments()
{
    return $this->hasMany('App\Investment');
}
Run Code Online (Sandbox Code Playgroud)

投资模式有:

public function project() {
    return $this->belongsTo('App\Project');
}
Run Code Online (Sandbox Code Playgroud)

项目表有字段 id、字段...

投资表包含字段 id、project_id、status、created_at

我的问题是,查询运行并返回至少有一项投资的项目集合,但是whereHas内的where子句被忽略,因为生成的集合包含状态值不同于paid 的投资。

有人知道发生了什么事吗?

plm*_*nts 5

我相信这就是你所需要的

$projects = Project::whereHas('investments', function($q) { 
          $q->where('status','=','paid'); 
     })->with(['investments' => function($q) { 
          $q->where('status','=','paid'); 
     }])->get();
Run Code Online (Sandbox Code Playgroud)

whereHas将检查所有有paid投资的项目,with并将立即加载所有这些投资。