0

Good day, basically I want to insert some related data all at once using eloquent. My current code is:

$allStudies = Study::chunk(50, function ($studies) use ($request, $questionData, $answerData) {
      foreach ($studies as $study) {
         $evaluationInsert = Evaluation::create([
              'study_id'      => $study->id,
              'questionnaire' => $request->questionnaire,
              'description'   => $request->description
         ]);

         $evaluationQuestions = $evaluationInsert
                                       ->question()
                                       ->createMany($questionData);

         foreach ($evaluationQuestions as $question) {
                  $question->answer()->createMany($answerData);
         }
      }
});

The result of $allStudies is a collection of Study model that currently have around 150-ish data. $questionData is just a static array of arrays that consist of 38 elements and $answerData is an array of arrays that have 4 elements which consist the answer options of each questions. However, the code does work but it takes too long time to execute because of big loops and increasing the timeout in php seems not an ideal way to solve this. What is the elegant way to solve this kind of case?

Rizky Irmawan
  • 67
  • 1
  • 8
  • 1
    Does this answer your question? [Bulk Insertion in Laravel using eloquent ORM](https://stackoverflow.com/questions/12702812/bulk-insertion-in-laravel-using-eloquent-orm) – Wesley Smith Oct 09 '20 at 06:53
  • I think it's different case from mine. My code does work but I always get a timeout exceed error (or warning I forgot) because of the loops I guess. – Rizky Irmawan Oct 09 '20 at 06:58
  • ca you use mongo(Jenssegers for Laravel), it is good for large databases, or postgresql which provides asynchronous calls to db. – bhucho Oct 09 '20 at 10:34
  • "mongo requires lesser input and output operations due to embedded data models, unlike relational databases. MongoDB indexes also support faster queries. " this is the exact statement of comparison between two – bhucho Oct 09 '20 at 10:35
  • you can visit this link https://blackdeerdev.com/laravel-chunk-vs-cursor/ – bhucho Oct 12 '20 at 14:59

0 Answers0