复制 AR 记录 &将其重新插入数据库

2022-01-04 00:00:00 database php yii activerecord

我有一个想要复制的 AR 模型,但只需要手动更改外键.

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']));

这个查询基本上是查询奖品表并获取特定比赛的所有行.对于奖品对象,我想基本上重新插入/复制相同的信息,除了我想手动设置的比赛 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.

我对基本上只有一行并且效果很好的 AR 对象做了类似的事情,但是在这种情况下,因为比赛可以有多个奖项,所以相同的代码不会.

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();

这很好用 - 我如何在奖品的集合"上修改它,并在设置我自己的competition_id"值时将其复制到数据库中.

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.

注意 - 我是 Yii 的新手,所以如果我犯了任何明显的错误/不好的做法,请告诉我

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

推荐答案

克隆不起作用.您需要将属性分配给新对象:

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();

相关文章