search

Home  >  Q&A  >  body text

php - Why does laravel only insert one piece of data each time?

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.

阿神阿神2765 days ago919

reply all(2)I'll reply

  • 習慣沉默

    習慣沉默2017-06-19 09:09:10

    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());
        }

    reply
    0
  • 世界只因有你

    世界只因有你2017-06-19 09:09:10

    Error message, table structure, diagram.

    reply
    0
  • Cancelreply