[英]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.