Yii2 - Model does not save in foreach loop in Yii2

I have a variable

I ran a foreach loop for each element

$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 element, which is #fourth_Tag. Can anyone solve this. Thanks in advance.

+6
source share
2 answers

I ran into exactly the same problem and got the perfect solution. This is verified.

 $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 create a new variable with the same name as the existing one, it overwrites its value. Here you do not need to create a new attribute or set id to null ; just unset() $model until the end of the foreach .

+2
source

Try it.

 $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; 
+3
source

All Articles