我正在創建一個應用程序,該應用程序中有一個簡單的多項選擇測驗功能。所以我有一個Question
實體和一個Answer
實體。我定義了2個關係,一對多(問題可以有很多答案)和一對一(問題可以有一個正確的答案)。以下是我迄今爲止:laravel保存一對一和一對多的關係
問題型號:
class Question extends Model
{
public $table = 'question';
public $primaryKey = 'question_id';
public $fillable = ['question', 'answer_id'];
public function answers()
{
return $this->hasMany('App\Models\Answer');
}
public function correctanswer()
{
return $this->hasOne('App\Models\Answer');
}
}
答型號:
class Answer extends Model
{
public $table = 'answer';
public $primaryKey = 'answer_id';
public $guarded = ['created_at', 'updated_at'];
public function question()
{
return $this->belongsTo('App\Models\Question');
}
public function correctquestion()
{
return $this->belongsTo('App\Models\Question');
}
}
而且在我的控制器:
$input = $request->all();
$answers = $input['answer'];
unset($input['answer']);
$question = Question::create($input);
foreach($answers as $key=>$a){
$arr['question_id'] = $question->question_id;
$arr['answer'] = $a;
$answer = new Answer($arr);
$question->answers()->save($answer); //save all answers - this works
if($key == 0){ //the first submitted answer is the correct one
$question->correctanswer()->save($answer); //save correct answer - this doesn't work
}
}
我的db表的定義:
CREATE TABLE IF NOT EXISTS question (
question_id int(11) unsigned NOT NULL AUTO_INCREMENT,
question text,
created_at timestamp,
updated_at timestamp,
answer_id int(11) unsigned,
PRIMARY KEY (question_id),
FOREIGN KEY (answer_id)
REFERENCES answer(answer_id)
ON DELETE NO ACTION
ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE IF NOT EXISTS answer (
answer_id int(11) unsigned NOT NULL AUTO_INCREMENT,
answer text,
created_at timestamp,
updated_at timestamp,
question_id int(11) unsigned,
PRIMARY KEY (answer_id),
FOREIGN KEY (question_id)
REFERENCES question(question_id)
ON DELETE CASCADE
ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
問題是我的問題實體沒有保存正確答案。所有的答案都在應答表中妥善保存,但我只需要做到這一點,所以我知道哪個是正確的。
任何人都可以看到我做錯了什麼?
在此先感謝!
你的控制器是一個部件,你會顯示完整的功能。 –
@KrisRoofe我加了剩下的部分,但我不認爲它會有所幫助,它只是從請求中獲取輸入。 – Sehael