Reputation: 8288
I have three database tables: users
, questions
and attempts
:
users
- id
questions
- id
- text
attempts
- id
- users_id
- questions_id
- correct
Every time a user attempts a question, that question's ID is added to attempts.question_id
and their id is added to attempts.users_id
.
A user can attempt a question any number of times.
Currently, I can retrieve all question attempts for a user with Eloquent:
In the User.php model:
public function attempts()
{
return $this->hasMany('Attempt', 'users_id');
}
I can get an attempt's question from the Attempt.php model like this:
public function question()
{
return $this->belongsTo('Question', 'questions_id');
}
What I need to do is get all questions answered by a user using Eloquent. I think this can be done using hasManyThrough()
but I can't figure out how to do (also, I have greatly simplified my tables here for illustration).
I want to be able to do this:
$answered_questions = User::answeredQuestions()->get();
Upvotes: 1
Views: 272
Reputation: 81187
You can't use hasManyThrough for this. This is many-to-many with pivot table, which is attempts here, so use this:
// User model
public function correctAnswers()
{
return $this->belongsToMany('Question', 'attempts', 'users_id', 'questions_id')
->wherePivot('correct','=',1)
->distinct();
}
public function answers()
{
return $this->belongsToMany('Question', 'attempts', 'users_id', 'questions_id')
->withPivot(['correct']);
->distinct();
}
This way you can access the relations like this:
$user->correctAnswers; // collection of Question models with correct answer
$user->answers; // collection of Question models
$user->answers->first()->pivot->correct; // returns 1 if the attempt was correct, otherwise 0 (suppose you have boolean/tinyint on that field)
Upvotes: 2