I have User
, Answer
, and Question
models. Answers belong to users and questions, i.e. the answers
table has a user_id
column and a question_id
column.
My User
model has a method to return all answered questions
class User extends Model {
public function answeredQuestions(){
return $this->hasManyThrough('App\Answer', 'App\Question');
}
}
I'd like to have another method to retrieve all unanswered questions, but I'm not sure how to go about that. As a workaround I can get it from the Question
model by passing in a user id like this:
class Question extends Model {
public function scopeUnanswered($query, $user_id){
return $query->whereDoesntHave('answers', function ($query) use ($user_id) {
$query->where('user_id', $user_id);
})->get();
}
}
I would prefer to access it via the User
model with $user->unansweredQuestions
though. Is this possible to do cleanly through the User model?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire