Yii Framework Forum: Cloning Activerecord / Behavior Issues - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Cloning Activerecord / Behavior Issues Rate Topic: -----

#1 User is offline   pommeverte 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 39
  • Joined: 15-March 11

Posted 18 January 2013 - 01:38 PM

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;
$AR2->save();

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

$AR2->attachBehaviors($AR2->behaviors());

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

#2 User is offline   pommeverte 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 39
  • Joined: 15-March 11

Posted 19 January 2013 - 07:37 AM

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
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users