2016-09-18 76 views
0

我想插入很多記錄到數據庫中一個一個動作。用yii2插入多個記錄到數據庫

在這個控制器我用的foreach用於插入到數據庫中,但只是最後一條記錄插入到數據庫中,我不知道爲什麼。我想插入全部記錄到數據庫。

我的控制器:

   if (isset($_POST['month'])) { 
        $name = $_POST['month']; 
        $price = $_POST['Request']; 
        $i = 0; 
        foreach ($name as $month) { 
         $model->month = $month; 
         $model->price = $price['price']; 
         $model->save(false); 
         $i++; 
        } 
         $pay_info = [ 
          'cost' => $price['price'], 
          'title' => 'title']; 
         return $this->render('payment', ['pay_info' => $pay_info]); 
       } 

回答

1

一個簡單的方法是基於你應該建立在你的foreach爲你想保存 每個實例的新模式的事實(控制器代碼是不完整的,所以我可以」知道你的模型)

   if (isset($_POST['month'])) { 
       $name = $_POST['month']; 
       $price = $_POST['Request']; 
       $i = 0; 
       foreach ($name as $month) { 
        $model = new YourModel(); /* here */ 
        $model->month = $month; 
        $model->price = $price['price']; 
        $model->save(false); 
        $i++; 
       } 
        $pay_info = [ 
         'cost' => $price['price'], 
         'title' => 'title']; 
        return $this->render('payment', ['pay_info' => $pay_info]); 
      } 

,但我也siggest探索batchInsert命令http://www.yiiframework.com/doc-2.0/yii-db-command.html#batchInsert()-detail

對於批量插入,你可以建立一個asscociative陣列月和價格例如:

$my_array= [ 
     ['January', 30], 
     ['Febrary', 20], 
     ['March', 25], 
    ] 

\Yii::$app->db->createCommand()-> 
     batchInsert('Your_table_name', ['month', 'price'],$my_array)->execute(); 
+0

謝謝它的作品。你能用batchinsert告訴我這個動作嗎? –

+0

我已更新答案.. – scaisEdge

+0

非常感謝。這很有用 –