Duplicate an AR record & re-insert this into the database Duplicate an AR record & re-insert this into the database database database

Duplicate an AR record & re-insert this into the database


Cloning won't work. You need to assign the attributes to a 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();


If a more generic way of duplicating a Model / ActiveRecord in Yii2 Framework is required, you might use this solution:

$copy = clone $model;$copy->isNewRecord = true;foreach ($model->getPrimaryKey(true) as $field => $value) {    unset($copy->{$field});}$copy->save();

GitHub issue discussion about duplicate models: https://github.com/yiisoft/yii2/issues/7544#issuecomment-77158479


The answer for my problem although Michiel above helped me out - alternatively if you wouldn't mind adding another answer i'll 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(); }