Cloning Activerecord / Behavior Issues

Hey guys, I was wondering if anyone had an easy way of cloning an active record?

Let me explain my issue:

Lets imagine my activerecord "AR" which has a behavior "BE" with a method "getOwnerId()" that simply returns $this->owner->id;

if I do the following:

$AR = AR::model()->findByPk(1);

$AR2 = clone $AR;

$AR2->id = null; // or unset($AR2->id);

$AR2->isNewRecord = true;


echo $AR->id; //echos 1

echo $AR2->id; //echos 2

echo $AR2->getOwnerId(); //echos 1 (incorrect - old id)

echo $AR->getOwnerId(); //echos 1 


echo $AR->id; //echos 1

echo $AR2->id; //echos 2

echo $AR2->getOwnerId(); //echos 2 

echo $AR->getOwnerId(); //echos 1 - for those who were curious 

I’m guessing that the behaviors point towards the initial object and aren’t refreshed/reset upon save(). Nor are they with refresh()

I can extend CActiveRecord to unset/reset behaviors or I could do it afterSave from within the behavior but both seem a little sloppy.

So my question is:

Is this desired behavior? If not is there any plan to implement a CActiveBehavior __clone() or a refreshBehaviors() or something?

If so, is there any cleaner way to do this than the stuff I mentioned above?

Ok, I’m adding more information here as issues arise because I believe CActiveRecord could really use a clone/duplicate method:

Sometimes with extensions, or external code, when you extend from another CActiveRecord child class these classes might store primary key and any extra ActiveRecord information seperately. This information is then cloned and never changed upon save(). As much as I agree that this is probably more of a specific issue with those extentions it still seems to me that the safest aproach with cloning is creating a new ActiveRecord and then copying all data over to it.

So far I can think of the following (bullet points so I/we can add as I go):

  • creating a new AR

  • Copying information from all relations in the old AR

If you can think of anything else Let me know