Farzan
(Farzan B)
1
Hi,
Assume you have a model which is an instance of CActiveRecord and you have an object which represents a row in the table of the model above.
Is it possible to use object cloning to duplicate the row in the table? Something like this:
$row = MyModel::model()->find();
$row2 = clone $row;
$row2->save();
If yes, what changes should I make to the cloned object before saving it?
u can use like this
$row = MyModel::model()->find();
$row2 = new MyModel;
$row2->attributes = $row->attributes
$row2->save();
l.jurgs
(L Jurgs)
3
You need to do 2 things
-
if the table has a primary key you must null out the attributes that represent it.
-
set isNewRecord to true.
Same as Rajith R with 2 additional assignments:
$row = MyModel::model()->find();
$row2 = new MyModel;
$row2->attributes = $row->attributes
$row2->id = null; //(if it's composite it's going to need more assignments than this)
$row2->isNewRecord = true;
$row2->save();
Clone works fine too but remember that CActiveRecord doesn’t implement a __clone() method so it’ll only perform a shallow copy.
@Luke Jurgs
I think , that s not needed…
l.jurgs
(L Jurgs)
5
Sorry you are correct about the isNewRecord part, shouldn’t answer questions on boards when tired.
l.jurgs
(L Jurgs)
6
This is what I meant:
$row = MyModel::model()->find();
$row->id = null; //(if it's composite it's going to need more assignments than this)
$row->isNewRecord = true;
$row->save();
This way you don’t even need a new instance or a copy of the attributes.
jcontesse
(Jcontess)
7
How can we modify this to include related rows (one to many)?
I am trying this but is not working:
$model = $this->loadModel($id, 'Entity')->with('related1,related2,related3');
$relatedData = array(
'related1' => $model->related1,
'related2' => $model->related2,
'related3' => $model->related3,
);
$model->id=null;
$model->isNewRecord = true;
$model->saveWithRelated($relatedData);
The main row works fine but not the related rows.