Ilyas karim
Ilyas karim

Reputation: 4812

Yii2 - Model is not saving in foreach loop in Yii2

I have a variable

I have run foreach loop for every item

$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.

Upvotes: 6

Views: 6094

Answers (2)

Sohel Ahmed Mesaniya
Sohel Ahmed Mesaniya

Reputation: 3450

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.

Upvotes: 3

GAMITG
GAMITG

Reputation: 3818

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;

Upvotes: 5

Related Questions