复制AR记录和重新插入到数据库中 [英] Duplicate an AR record & re-insert this into the database

查看:193
本文介绍了复制AR记录和重新插入到数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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();

这篇关于复制AR记录和重新插入到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆