Cascade Delete The Child Record Using Relation Model Function

I have table with column id, name and parentid

Here, id and parentid have child-parent relation.

How can I define the relation in model so that on deleting one id, it deletes other row which have parentid with same id. The following action delete only one record but not it’s child record.




	public function actionDelete($id)

	{

		$this->loadModel($id)->delete();


		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser

		if(!isset($_GET['ajax']))

			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

	}



Hi sunil,

I’m not sure that you can define a model relation that will delete child records. I prefer to use the ON DELETE CASCADE option for table relations to delete child records. You can easily add this to the createTable method in your childs yii migration file[size=“2”] like this:[/size]


'parent_id' => 'integer NOT NULL REFERENCES tbl_parent(id) ON DELETE CASCADE',

After migrating down and up again, you can delete a parent record, and all child records should be automatically deleted by the database as well.

You could also use your parent model to delete child records. Though I don’t believe this is the best way, you could do something like this in your parent model:




$private $cacheId


public function beforeDelete()

{

	$this->cacheId = $this->id;


	return parent::beforeDelete();

}


public function afterDelete()

{

	$children = Child::model()->findAll(

		'parent_id=:parentId',

		array(

			':parentId'=>$this->cacheId

		)

	);


	foreach($children as $child)

	{

		$child->delete();

	}


	parent::afterDelete();

}