I have a variable
我有一个变量
I have run foreach loop for every item
我已经为每个项目运行了foreach循环
$tags = ['#first_Tag','#second_tag','#third_tag','#fourth_Tag'];
foreach ($tags as $t) :
$model = new Tags;
$model->tag_name = $t;
$model->save(); //yii2
endforeach;
this function only saves the last item which is #fourth_Tag. Can any one have solution about this. Thanks in advance.
这个函数只保存最后一个条目#fourth_Tag。有人能解决这个问题吗?提前谢谢。
2 个解决方案
#1
2
I encountered exactly same problem and got perfect solution. This is tested.
我遇到了同样的问题,得到了完美的解决方案。这是测试。
$tags = ['#first_Tag','#second_tag','#third_tag','#fourth_Tag'];
foreach ($tags as $t) :
$model = new Tags;
$model->tag_name = $t;
$model->save(); //yii2
unset($model);
endforeach;
This is when you make a new variable with the same name of existing one, it overwrite its value. Here you don't need to make new attribute or set id to null
; just unset()
$model
before the end of foreach
loop.
这是当您创建一个具有相同名称的新变量时,它会覆盖它的值。这里不需要新建属性或将id设置为null;只是在foreach循环结束之前unset() $model。
#2
3
Try this..
试试这个. .
$tags = ['#first_Tag','#second_tag','#third_tag','#fourth_Tag'];
$model = new Tags;
foreach ($tags as $t) :
$model->id = NULL; //primary key(auto increment id) id
$model->isNewRecord = true;
$model->tag_name = $t;
$model->save(); //yii2
endforeach;
#1
2
I encountered exactly same problem and got perfect solution. This is tested.
我遇到了同样的问题,得到了完美的解决方案。这是测试。
$tags = ['#first_Tag','#second_tag','#third_tag','#fourth_Tag'];
foreach ($tags as $t) :
$model = new Tags;
$model->tag_name = $t;
$model->save(); //yii2
unset($model);
endforeach;
This is when you make a new variable with the same name of existing one, it overwrite its value. Here you don't need to make new attribute or set id to null
; just unset()
$model
before the end of foreach
loop.
这是当您创建一个具有相同名称的新变量时,它会覆盖它的值。这里不需要新建属性或将id设置为null;只是在foreach循环结束之前unset() $model。
#2
3
Try this..
试试这个. .
$tags = ['#first_Tag','#second_tag','#third_tag','#fourth_Tag'];
$model = new Tags;
foreach ($tags as $t) :
$model->id = NULL; //primary key(auto increment id) id
$model->isNewRecord = true;
$model->tag_name = $t;
$model->save(); //yii2
endforeach;