在 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)
它returns
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"];
}
}
我有一个数组,但是在保存记录时只保存了最后一条记录
这是我的代码
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)
它returns
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"];
}
}