如何使用 Eloquant 插入多级条目?

让我们考虑一下我有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'])

         ]

      ])

   ]

]


阿晨1998
浏览 74回答 1
1回答

12345678_0001

仅使用静态值进行测试:$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)设置值
打开App,查看更多内容
随时随地看视频慕课网APP