laravel 5.6 bulk inserting json data

后端 未结 5 840
無奈伤痛
無奈伤痛 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:35

    Try code below

    $jsonarray =json_decode(json_encode($b),TRUE); // $b=your json array
    foreach ($jsonarray as $key => $value) 
    {
     foreach ($value as $a => $b) 
      {
      $qry=DB::insert('insert into your_table(colomn_name1,colomn_name2)values(?,?)',[$b['indexname1'],$b['indexname2']]); //index name will be paper_id,question_no etc
      }
    }
    

    your code will look like this

    public function bulkdata(Request $request)
      {
    
       $b=$request->input('data');
    $jsonarray =json_decode(json_encode($b),TRUE);
    foreach ($jsonarray as $key => $value) 
    {
    
     foreach ($value as $a => $b) 
      {
    
      $qry=DB::insert('insert into yourtable(paper_id,question_no,question,answer1,answer2,answer3,answer4,answerC,knowarea)values(?,?,?,?,?,?,?,?,?)',[$b['paper_id'],$b['question_no'],$b['question'],$b['answer1'],$b['answer2'],$b['answer3'],$b['answer4'],$b['answerC']$b['knowarea']);
      }
    }         
    
    }
    

提交回复
热议问题