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

2020-03-09 18:24发布

I have a AR model that I am trying to duplicated 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 prizes table and gets all the rows for a particular competition. With the prizes object I would like to basically re-insert/duplicate the same information except the competition id which I want to manually set.

I did something similar for an AR object that basically only has one row and that worked well, however in this instance as a competition can have more than one prize this same code won't.

// 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 would I modify this on a 'collection' of prizes and have this duplicated into the database while setting my own 'competition_id' value.

Note - i'm to new to Yii, so please let me know if I have made any obvious errors/bad practice

4条回答
smile是对你的礼貌
2楼-- · 2020-03-09 18:39

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();
查看更多
冷血范
3楼-- · 2020-03-09 18:41

How about (yii2 syntax):

$model=Competitions::findOne([':competition_id' => $post['competition_id']]);
$model->id = null;
$model->isNewRecord = true;
$model->save();
查看更多
欢心
4楼-- · 2020-03-09 18:44

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(); 
}
查看更多
贼婆χ
5楼-- · 2020-03-09 18:49

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

查看更多
登录 后发表回答