Reputation: 5083
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()
Upvotes: 3
Views: 8796
Reputation: 1248
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());
});
Upvotes: 10
Reputation: 13259
What about
return $this->questions->where('survey_id', Survey::current()->id);
Upvotes: 0