Php 在yii2中保存多条记录
我有一个数组,但保存记录时只保存最后一条记录 这是我的密码Php 在yii2中保存多条记录,php,yii2,yii2-advanced-app,Php,Yii2,Yii2 Advanced App,我有一个数组,但保存记录时只保存最后一条记录 这是我的密码 if (isset($arr["transporters"])) { foreach ($arr["transporters"] as $other) { $model->company_name = $other["transportername"]; if($model->save()){
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\u 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"];
}
}
在这种情况下,每次要保存不同的数据库行时,都需要在循环中创建
$model
的新实例。我发现它现在可以工作了