Where clause inside whereHas being ignored in Eloquent

给你一囗甜甜゛ 提交于 2019-12-24 06:34:48

问题


Im trying to make a query using whereHas with eloquent. The query is like this:

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

Im using Laravel 5.2 using a Postgres driver.

The Project model is:

public function investments()
{
    return $this->hasMany('App\Investment');
}

The investments model has:

public function project() {
    return $this->belongsTo('App\Project');
}

The projects table has fields id,fields...

The investments table has the fields id,project_id,status,created_at

My issue is that the query runs and returns a collection of the projects which have at least one investment, however the where clause inside the whereHas is ignored, because the resulting collection includes investments with status values different than paid.

Does anyone has any idea of what is going on?


回答1:


I believe this is what you need

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

whereHas wil check all projects that have paid investments, with will eagerload all those investments.




回答2:


You're confusing whereHas and with.

The with method will let you load the relationship only if the query returns true.

The whereHas method will let you get only the models which have the relationship which returns true to the query.

So you need to only use with and not mix with with whereHas:

$projects = Project::with(['investments' => 
function($query){ $query->where('status','=','paid'); }])
->get();



回答3:


Try like this:

$projects = Project::with('investments')->whereHas('investments', function($q) {
                $q->where('status','like','paid'); //strings are compared with wildcards.
            })
            ->get();



回答4:


Change the order. Use with() before the whereHas(). I had a similar problem few weeks ago. Btw, is the only real difference between the problem and the functional example that you made.



来源:https://stackoverflow.com/questions/43310777/where-clause-inside-wherehas-being-ignored-in-eloquent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!