laravel 5.6 bulk inserting json data

后端 未结 5 865
無奈伤痛
無奈伤痛 2021-01-05 14:21

I am trying to build an API to store and retrieve MCQ exam papers. I am using laravel resource class to send handle Json data. I need to insert 40 records into MySQL databas

5条回答
  •  南方客
    南方客 (楼主)
    2021-01-05 14:36

    Based on your sample data, you can json_decode the data and then use a single Model::insert():

    {
      "data":[
        {
          "paper_id":"5",
          "question_no":"2",
          "question":"test insert code",
          "answer1":"answer1",
          "answer2":"answer2 ",
          "answer3":"answer3 ",
          "answer4":"Answer4 ",
          "answerC":"Correct Answer",
          "knowarea":"who knows!"
        },
        ...
      ]
    }
    
    // Controller.php
    public function store($json)
    {
        $data = json_decode($json, true);
        Paper::insert($data);
    }
    

    That will create arrays from your json and then insert all the records at once.

提交回复
热议问题