簡體   English   中英

在yii2中保存多條記錄

[英]Saving multiple records in yii2

我有一個數組,但保存記錄時只保存最后一條記錄

這是我的代碼

        if (isset($arr["transporters"])) {

           foreach ($arr["transporters"] as $other) {
                $model->company_name = $other["transportername"];
                if($model->save()){
                $allsaved = true;
                 }

            }
            if($allsaved){
                return ['data' => "Successifully created"];
            }else{
                return ['data' => "Sorry an error occured when saving the transporters"];
            }
        }

通過var_dump($arr)

它返回

array(1) {
 ["transporters"]=>
 array(2) {
  [0]=>
   array(1) {
    ["transportername"]=> string(2) "news"  //its not saved
  }
  [1]=>
   array(1) {
     ["transportername"]=> string(4) "event"  //only this one gets saved
   }
 }
}

為什么我不能保存多條記錄

添加適當的新模型並正確彈出

  if (isset($arr["transporters"])) {

       foreach ($arr["transporters"] as $other) {
            $model = new YourModel(); // add new model 
            $model->company_name = $other["transportername"];
            ..... 
            $model->others_column  // remdeber to properly populated  with all the value you needd
            .......
            if($model->save()){
            $allsaved = true;
             }

        }
        if($allsaved){
            return ['data' => "Successifully created"];
        }else{
            return ['data' => "Sorry an error occured when saving the transporters"];
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM