我已经尝试了10次,但仍然无法做到。所以这就是我想要做的事情。
我试图插入一个有多个问题且每个问题都有多个选项的测验。
测验 - 有很多 - > 问题 - 有很多 - >的选项
例如:
This is a Quiz?
Question 1?
Option 1
Option 2
Question 2?
Option 1
Option 2
我有3个表来存储Quiz Questions and Answers
。所有这些都正确链接,我可以毫无问题地获取和显示测验。
但我想插入一个测验。我知道如何插入数据与单个有很多关系,但绝对不知道如何插入2个或更多的数据有很多关系。
$quiz = new Quiz;
...
$quiz->save();
$questions = [new Question, new Question, ...];
$quiz->questions()->saveMany($questions);
我能够插入与该测验相关的测验和多个问题,但现在我还想为每个问题插入多个选项,例如$options1, $options2
等。
我是laravel的新手。
答案 0 :(得分:1)
你需要有这样的东西
class Quiz extends Eloquent {
protected $table = "you table name here";
public function questions() {
return $this->hasMany("Question", "question_id", "id");
//where Question is your model for questions table
}
}
class Question extends Eloquent {
protected $table = "you table name here";
}
$quiz = new Quiz;
//set quiz data here
// $quiz->name = "name";
$quiz->save();
for ($i = 0; $i < count($questions); $i++) {
$arr[$i] = new Question;
$arr[$i]->quize_id = $quiz->id;;
// Set other data here
}
$quiz->questions()->saveMany($arr);