让我们考虑一下我有Quizzes可以包含Questions其中每个都包含一些Propositions. 因此我有三个模型:Quiz、Question和Proposition。这些命题通过包含以下内容的数据透视表链接到问题:id_question, id_proposition, is_correct。
在 Seeder 中,我想插入一个虚拟测验,可以用 YAML 表示,如下所示:
title: A Quiz
questions:
- name: Animals
content: What's the difference between a duck?
propositions:
- text: The dog has two legs
is_correct: false
- text: One leg is both the same
is_correct: true
- text: Every duck has at least several teeth
is_correct: false
传统上,在 Laravel 中,您需要拆分每个步骤,例如:
$quiz = new Quiz;
$quiz->name = "A Quiz";
$question = $quiz->questions()->create();
...
是否有更短的方法来分层创建一个新条目,如下所示:
Quiz::create([
'name' => 'A Quiz'
'questions' => [
Question::Create([
'name' => 'Animals',
'content' => "What's the difference between a duck?"
'propositions' => [
Proposition::Create(['content' => 'The dog has two legs']),
Proposition::Create(['content' => 'One leg is both the same'])
Proposition::Create(['content' => 'Every duck has at least several teeth'])
]
])
]
]
12345678_0001