Question

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...?

Was it helpful?

Solution

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.

OTHER TIPS

You might want to try this:

// Reset primary key
$this->_primary_key_value = NULL;

And do not forget about Object cloning: Object Cloning

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top