I'd like to "duplicate" an ORM object and then save it into the database (with a new primary key), but I am not able to unset the primary key of the copied object.
$orm1 = new Model1($id);
if($orm1->loaded()) {
$orm2 = $orm1;
$orm2->id = null; //something like this?
unset($orm2->_primary_key); //or like this?
$orm2->save(); //I would like to create a new entry in the db but it doesn't work
}
I hope I am clear enough... Basically, how can I "save again" a model in the db...?
You need to copy ORM data from one model to another:
// save current data
$data = $orm1->as_array();
$orm2 = new Model1();
$orm2->values($data);
$orm2->save();
This example uses separate ORM objects. You can load values back to $orm1
, but don't forget to call $orm1->clear()
before $orm1->values($data)
. This resets the model to its unloaded state.
Note that as_array
will also return belongs_to
relationships.