Please Help, Cloning Parent And Child Db Records


Apologies i’m relatively new to the framework and have a question about cloning DB records.

I have successfully managed to clone a parent record, but I’m really struggling to clone the parents child records.

I’m working on an inventory system and each parent record hase multiple children, I wondered if anyone could post me some example code for model and controllers to help me out or point me in the direction of a good example?

Many thanks in advance…

I don’t know of an existing example but here is one I quickly whipped up for you


// User model

public function relations()


	return array(

		'children'=>[self::HAS_MANY, 'User', 'parent']



// User contorller

public function actionClone()


	$user = User::model()->findByPk($id);

	// clone parent record

	$parentUser = new User;

	$parentUser->attributes = $user->attributes;


	// clone child records

	foreach ($user->children as $child)


		$childUser = new User;

		$childUser->attributes = $child->attributes;

		// update the parent to newly created parent

		$childUser->parent = $parentUser->id;