简体   繁体   中英

Can this query be handled using Laravel's Eloquent hasManyThrough() relationship or will a raw database query be required?

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();

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM