我有三个数据库表:users
,questions
和attempts
:
users
- id
questions
- id
- text
attempts
- id
- users_id
- questions_id
- correct
每次用户尝试提问时,该问题的ID都会添加到attempts.question_id
,并且他们的ID会添加到attempts.users_id
。
用户可以多次尝试问题。
目前,我可以使用Eloquent检索用户的所有问题尝试:
在User.php模型中:
public function attempts()
{
return $this->hasMany('Attempt', 'users_id');
}
我可以从Attempt.php模型中得到一个尝试的问题:
public function question()
{
return $this->belongsTo('Question', 'questions_id');
}
我需要做的是使用Eloquent让用户回答所有问题。我认为这可以使用hasManyThrough()
来完成,但我无法弄清楚该怎么做(另外,我在这里大大简化了我的表格以供说明)。
我希望能够做到这一点:
$answered_questions = User::answeredQuestions()->get();
答案 0 :(得分:2)
您无法使用hasManyThrough。 这是带有数据透视表的多对多,这是尝试,所以请使用:
// 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)