php - Why does laravel only insert one piece of data each time?
阿神
阿神 2017-06-19 09:07:10
0
2
892

DB::beginTransaction(); After it is turned on, only the first piece of data can be inserted each time, and the rest will be rolled back.
code show as below:

try {
     DB::beginTransaction();
     foreach ($rightOrWrongRows as $row) {
     $question = array_combine($rightOrWrongHeader, $row);
     RightOrWrong::create([
         'question' => $question['question'],
         'answer' => $question['answer'],
         'scope' => $question['scope'],
         'degree' => 1,
         'exam_id' => $this->examId,
        ]);
     }
     DB::commit();
     } catch (\Exception $exception) {
        DB::rollBack();
        Log::info($exception->getMessage());
    }

If you close the transaction, you can insert multiple pieces of data

try {
     //DB::beginTransaction();
     foreach ($rightOrWrongRows as $row) {
     $question = array_combine($rightOrWrongHeader, $row);
     RightOrWrong::create([
         'question' => $question['question'],
         'answer' => $question['answer'],
         'scope' => $question['scope'],
         'degree' => 1,
         'exam_id' => $this->examId,
        ]);
     }
     //DB::commit();
     } catch (\Exception $exception) {
        //DB::rollBack();
        Log::info($exception->getMessage());
    }

Please help me solve this problem, I am a newbie.

阿神
阿神

闭关修行中......

reply all(2)
習慣沉默

try

try {
     DB::beginTransaction();
     $data = [];
     foreach ($rightOrWrongRows as $row) {
         $question = array_combine($rightOrWrongHeader, $row);
         $data[] = [
             'question' => $question['question'],
             'answer' => $question['answer'],
             'scope' => $question['scope'],
             'degree' => 1,
             'exam_id' => $this->examId,
             'created_at' => date('Y-m-d H:i:s'),
             'updated_at' => date('Y-m-d H:i:s'),
            ]);
     }
     RightOrWrong::insert($data);
     DB::commit();
     } catch (\Exception $exception) {
        DB::rollBack();
        Log::info($exception->getMessage());
    }
世界只因有你

Error message, table structure, diagram.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template