Laravel使用Eloquent插入具有两个具有许多关系的数据


Laravel Insert Data with Two Has Many Relationships using Eloquent

我已经试了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等。

我是拉拉韦尔的新手。

您将需要像这样的

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