Laravel Eloquent 关系(需要咨询)

Laravel Eloquent relations (need advice)

我在处理 Laravel Eloquent 关系时遇到问题 我了解它们的工作原理,但我不知道如何正确地 "use" 它们,所以我需要一些 guidance/pointers。就这样吧。

我有考试 table

Schema 看起来像(感谢 lukasgeiter)

考试

id
title
duration

问题

id
text
exam_id

答案

id
text
question_id
correct (boolean)

关系:

考试模型

public function questions(){
    return $this->hasMany('Question');
}

问题模型

public function answers(){
    return $this->hasMany('Answer');
}

 public function exam(){
    return $this->belongsTo('Exam');
}

答案模型

 public function question(){
   return $this->belongsTo('Question');
}

我理解这部分,但现在我希望用户能够解决考试并存储该数据(我需要保存用户的答案,例如 user_id 1,exam_id 2 ,question_id1,回答正确)。我已经这样做了,但我认为这是错误的(是的,它确实有效,但我认为它不是正确的方法)

架构看起来像

用户

id
email
pass
...

已解决的考试

id
user_id
exam_id (havent put relation here not sure if needed)
solved (boolean) // if its completed right or wrong

已解决问题

id
exam_id (havent put relation here not sure if needed)
answer(boolean)(then later i check this boolean with answers) //if the answer is right or wrong

现在对于关系我已经按照我之前说的做了

用户模型

public function SolvedExams() {

    return $this->hasMany('SolvedExams');
}

已解决考试模型

public function User() {
    return $this->belongsToMany('User');
}

public function questions() {

    return $this->hasMany('solved');
}

SolvedQuestions 模型

public function exam() {
    return $this->belongsTo('SolvedExam');
}

这是正确的方法还是我做错了(而且我是关系的初学者)

我觉得你很接近...

我会这样做:

表格

考试

id, title, duration

问题

id, text, exam_id

答案

id, text, question_id, correct

用户

id, email, password

尝试

id, user_id, exam_id

answers_try(枢轴table)

id, try_id, answer_id

关系

考试

public function questions(){
    return $this->hasMany('Question');
}

public function tries(){
    return $this->hasMany('Try');
}

问题

public function answers(){
    return $this->hasMany('Answer');
}

public function exam(){
    return $this->hasMany('Exam');
}

回答

public function question(){
    return $this->belongsTo('Question');
}

public function tries(){
    return $this->belongsToMany('Try');
}

用户

public function tries(){
    return $this->hasMany('Try');
}

尝试

public function answers(){
    return $this->belongsToMany('Answer');
}

public function user(){
    return $this->belongsTo('User');
}


public function exam(){
    return $this->belongsTo('Exam');
}

用法

获取用户对问题的回答

$answer = User::find(1)
              ->tries()->where('exam_id', 2)->first()
              ->answers()->where('question_id', 3)->first();

创建新考试

$exam = new Exam;
$exam->save();

$question = new Question;
$question->text = 'Foo?';
$exam->questions()->save($question);

$answer1 = new Answer;
$answer1->text = 'Foo!';
$answer1->correct = true;

$answer2 = new Answer;
$answer2->text = 'Bar!';
$answer2->correct = false;

$question->answers()->saveMany([$answer1, $answer2]);

正在保存用户答案

$exam = Exam::find(1);
$user = Auth::user();
$try = new Try;
$try->user()->associate($user)->save();
$exam->tries()->save($try);

$try->answers()->attach(2); // 2 is the answer id