Eloquent / Laravel - Putting a WHERE Clause on a Reference Table With Chained Relationships

- 1 answer

Ad

I have the following relationship functions in my Job model:

public function resourceTypes(){

    return $this->belongsToMany('ResourceType', 'job_requests');

}

public function resources(){

    return $this->belongsToMany('Resource', 'jobs_resources')->withPivot('flow_type', 'resource_type_id');

}

I am able to get an object with data from both of the above relationships using:

$job = Job::findorfail($projectId);
$result = $job->with('resources.resourceTypes')->get();

I would like to put a where clause on the jobs_resources pivot table - specifically on the column flow_type.

How would I do this?

Ad

Answer

Ad

I ended up using the following statement:

Job::with(['resources' => function ($query){
   $query->wherePivot('flow_type', '=', '1' );
}, 'resources.resourceTypes'])->where('id', $projectId)->firstOrFail();
Ad
source: stackoverflow.com
Ad