mikelovelyuk
mikelovelyuk

Reputation: 4152

Eager load using where relationship on hasManyThrough

Using Laravel 5.2.

I have 3 Models; Survey, Group and Question.

I can define my Survey model as follows;

class Survey extends Model
{
    public function groups()
    {
        return $this->hasMany('App\Models\Group', 'survey_id');
    }

    public function questions()
    {
        return $this->hasManyThrough('App\Models\Question', 'App\Models\Group');
    }
}

and then in my controller I can do;

$survey = Survey::where('slug', $surveySlug)->first();

$survey->load('groups', 'questions');

dd($survey);

to eager-load all the associated groups and questions for a survey. but is it possible to eager-load only the groups and questions for one particular group? (so 1 survey, 1 group, but multiple questions)??

In my controller I have access to the current group via $groupSlug which is defined as slug in the groups table. So how can I use that?

I have a feeling it might something to do with constraining eager loads but I can't figure it out.

Upvotes: 1

Views: 381

Answers (1)

tommy
tommy

Reputation: 3625

Using eager load constraints:

$survey = Survey::with(['questions' => function($query) use ($groupSlug) {
    $query->where('groups.slug', $groupSlug);
}, 'groups' => function($query) use ($groupSlug) {
    $query->where('groups.slug', $groupSlug);
}])->whereSlug($surveySlug)->first();

This is not pretty to look at but is very elegant and does the job perfectly. Not changes to the model required for this.

Upvotes: 1

Related Questions