Laravel Eloquent关系(需要建议)

时间:2015-01-13 06:48:47

标签: mysql laravel eloquent

我对Laravel Eloquent关系有疑问我明白他们是如何工作但我不知道如何使用"他们是正确的,所以我需要一些指导/指示。所以这里。

我有考试表

架构看起来像(感谢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_id 1,answer true)。我这样做了,但我觉得它错了(是的它确实有效,但我不认为它是正确的方式)

架构看起来像

用户

id
email
pass
...

SolvedExams

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

SolvedQuestions

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');
}

SolvedExam模型

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

public function questions() {

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

SolvedQuestions模型

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

这是正确的方式还是我做错了(我是一个有关系的乞丐)

1 个答案:

答案 0 :(得分:2)

我认为你非常接近......

我这样做:

考试

id, title, duration

问题

id, text, exam_id

答案

id, text, question_id, correct

用户

id, email, password

尝试

id, user_id, exam_id

answers_try(数据透视表)

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