【发布时间】:2015-03-11 01:37:14
【问题描述】:
我在使用 Laravel Eloquent 关系时遇到问题,我了解它们是如何工作的,但我不知道如何正确“使用”它们,所以我需要一些指导/指针。所以就这样吧。
我有考试桌
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_id 1、答案为真)。我已经这样做了,但我认为它是错误的(是的,它确实有效,但我认为它不是正确的方法)
架构看起来像
用户
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');
}
SolvedExam 模型
public function User() {
return $this->belongsToMany('User');
}
public function questions() {
return $this->hasMany('solved');
}
已解决问题模型
public function exam() {
return $this->belongsTo('SolvedExam');
}
这是正确的方式还是我做错了(我是关系初学者)
【问题讨论】:
-
answer布尔值到底是什么?它不应该是答案表的外键吗?或者这只是用户的判断是对还是错? -
很抱歉会编辑它,不管它是对是错
-
好的,一个用户可以多次做同一个考试吗?
-
2 次...如果他低于 50%,第二次给出他第一次做错的问题,这就是为什么我在已解决的考试中使用已解决的列的原因