讓我們考慮一下我有Quizzes可以包含Questions其中每個都包含一些Propositions. 因此我有三個模型:Quiz、Question和Proposition。這些命題通過包含以下內(nèi)容的數(shù)據(jù)透視表鏈接到問題: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傳統(tǒng)上,在 Laravel 中,您需要拆分每個步驟,例如: $quiz = new Quiz; $quiz->name = "A Quiz"; $question = $quiz->questions()->create(); ...是否有更短的方法來分層創(chuàng)建一個新條目,如下所示: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條經(jīng)驗 獲得超5個贊
僅使用靜態(tài)值進行測試:
$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 根據(jù) YAML 索引值(類似于 json)設(shè)置值
- 1 回答
- 0 關(guān)注
- 134 瀏覽
添加回答
舉報
0/150
提交
取消