Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 901
Zabs Avatar asked Jan 08 '14 12:01

Zabs


People also ask

How do you duplicate a record in rails?

You generally use #clone if you want to copy an object including its internal state. This is what Rails is using with its #dup method on ActiveRecord. It uses #dup to allow you to duplicate a record without its "internal" state (id and timestamps), and leaves #clone up to Ruby to implement.


1 Answers

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();
like image 66
Michiel Avatar answered Oct 14 '22 16:10

Michiel