让我们考虑一下我有Quizzes可以包含Questions其中每个都包含一些Propositions. 因此我有三个模型:Quiz、Question和Proposition。这些命题通过包含以下内容的数据透视表链接到问题:id_question, id_proposition, is_correct。在 Seeder 中,我想插入一个虚拟测验,可以用 YAML 表示,如下所示:title: A Quizquestions: - 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']) ] ]) ]]
1 回答
12345678_0001
TA贡献1802条经验 获得超5个赞
仅使用静态值进行测试:
$quiz = Quiz::create([
'name' => 'A quiz',
])->questions()->createMany([
['name' => 'animals', 'content' => 'animals content'],
['name' => 'fruits', 'content' => 'fruits content'],
])->map(function($value, $key){
$value->propositions()->createMany([
['content' => 'content 1'],
['content' => 'content 2'],
]);
});
我认为你可以使用 foreach 根据 YAML 索引值(类似于 json)设置值
- 1 回答
- 0 关注
- 73 浏览
添加回答
举报
0/150
提交
取消