6

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.

3
  • 1
    Please show Tags model code. Commented Aug 23, 2015 at 11:36
  • 2
    $model->save() should return true if model has been saved, false otherwise. Test for it and if it returns false, do print_r($model->errors) to see what is wrong. Commented Aug 23, 2015 at 19:00
  • I haved used this problem and it worked correctly..... thanks Commented Aug 24, 2015 at 8:36

2 Answers 2

5

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;
Sign up to request clarification or add additional context in comments.

2 Comments

hai gamitg I tried your code..itz really working..but itz create an extra filed in my DB.Can you say Y itz happend???
its do not create extra field but it creates new row for new record.
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.