0

我想“复制”一个 ORM 对象,然后将其保存到数据库中(使用新的主键),但我无法取消设置复制对象的主键。

    $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
    }

我希望我足够清楚......基本上,我怎样才能在数据库中“再次保存”一个模型......?

4

2 回答 2

4

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.

于 2012-11-26T10:42:55.487 回答
-1

你可能想试试这个:

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

不要忘记对象克隆:对象克隆

于 2012-11-26T03:56:42.263 回答