yii2batch-insert

how to create batch insert in yii2


how to create batch insert

view

two input number check and tow input price check and tow input date check

<input type='text' name="number_check[]">
<input type='text' name="price_check[]">
<input type='text' name="date_check[]">
<input type='text' name="number_check[]">
<input type='text' name="price_check[]">
<input type='text' name="date_check[]">

controller

I don't know what to write ?????

Yii::$app->db->createCommand()->batchInsert('sale_check',[
'number_check',
'price_check',
'date_check', 
'user_id', 
'sale_id', 
],$data)->execute() ;

Solution

  • Looking to you sample where you have just two set of same fields you shoul populate the $data array and perform execute() of db command

      $post = Yii::$app->request->post();
    
      for ($i=0; $i<2; $i++){
        $data[$i][0] = $post[number_check][$i];
        $data[$i][1] = $post[price_check][$i];
        $data[$i][2] = $post[date_check][$i]; 
        $data[$i][3] = Your_value_for_user_id; 
        $data[$i][4] = Your_value_for_sale; 
      }
    
      Yii::$app->db->createCommand()->batchInsert('sale_check',[
        'number_check',
        'price_check',
        'date_check',
      ],
      $data
      )->execute();