Duplicate the AR record and paste it into the database

I have an AR model that I am trying to duplicate, but just need to manually change the foreign key.

$_POST['competition_id'] = 99; $prizes = CompetitionPrizes::model()->findAll('competition_id =:competition_id',array(':competition_id'=> $_POST['competition_id'])); 

This query basically queries the prize table and retrieves all rows for a specific competition. With the prize object, I would basically reinsert / duplicate the same information except the contest identifier that I want to set manually.

I did something similar for an AR object that basically only has one line, and it worked fine, however, in this case, since a competitor can have more than one prize, the same code will not.

 // My existing code for duplication process $obj = Competitions::model()->find('competition_id=:competition_id', array(':competition_id' => $post['competition_id'])); $clone = clone $obj; $clone->isNewRecord = true; unset($clone->competition_id); // i want to remove this so it is auto inserted instead via the db $clone->save(); 

This works great - how can I change this in the "collection" of prizes and duplicate it in the database when setting my own value "contest_id".

Note. I will be familiar with Yii, so please let me know if I made any obvious mistakes / bad practice.

+6
source share
3 answers

Cloning will not work. You need to assign attributes to the new object:

 $obj = Competitions::model()->find('competition_id=:competition_id', array(':competition_id' => $post['competition_id'])); $clone = new Competitions; $clone->attributes = $obj->attributes; $clone->save(); 
+18
source

How about (yii2 syntax):

 $model=Competitions::findOne([':competition_id' => $post['competition_id']]); $model->id = null; $model->isNewRecord = true; $model->save(); 
+3
source

The answer to my problem, although Michiel above helped me - alternatively, if you do not mind adding another answer, I will give you the accepted answer.

 foreach($models as $model) { $clone = new Competitions; $clone->attributes = $model->attributes; $clone->competition_id = '123' // custom var i am setting manually. $clone->save(); } 
+2
source

All Articles