Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel get collection of models where relation has value

I am trying to make a more elaborate registration form for my Laravel web app.
I have a Category, Question and Survey model.
A category hasMany Question's and a Question belongsTo a Survey.

Category class:

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

public function getUsingAttribute()
{
    return $this->questions->contains('survey_id', Survey::current()->id);
}

I do currently have a using attribute in my Category class but I would like to make this a scope.
To be clear, the expected return of Category::using->get() would return all Category where at least one of the questions has a survey_id of Survey::current()

like image 301
milo526 Avatar asked Dec 17 '25 21:12

milo526


1 Answers

I would do it with one of the the methods available to query a relationship existence, specifically the whereHas() method:

return $this->whereHas('questions', function ($query){
    $query->where('survey_id', Survey::current());
});
like image 146
Jean-Philippe Murray Avatar answered Dec 20 '25 17:12

Jean-Philippe Murray