我有三个数据库表:usersquestionsattempts

users
- id

questions
- id
- text

attempts
- id
- users_id
- questions_id
- correct

每次用户尝试一个问题时,该问题的ID都会添加到attempts.question_id中,而他们的ID也会添加到attempts.users_id中。
用户可以尝试任何次数的问题。
目前,我可以检索一个用户的所有问题尝试:
在User.php模型中:
public function attempts()
{
    return $this->hasMany('Attempt', 'users_id');
}

我可以从attain.php模型中得到一个attain的问题,如下所示:
public function question()
{
    return $this->belongsTo('Question', 'questions_id');
}

我需要做的是让用户用口才回答所有问题。我认为这可以使用hasManyThrough()来完成,但我不知道该怎么做(而且,为了便于说明,我已经大大简化了这里的表)。
我想做到这一点:
$answered_questions = User::answeredQuestions()->get();

最佳答案

你不能用hasManyThrough来做这个。
对于pivot table,这是一种多对多的尝试,因此请使用:

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

这样您就可以这样访问关系:
$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)

关于php - 可以使用Laravel的Eloquent hasManyThrough()关系处理此查询,还是需要原始数据库查询?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23457373/

10-12 00:16
查看更多