deletable-behavior delete many models with all relatives in one shot

  1. Requirements
  2. Usage
  3. Resources

Deletable behavior helps delete many models with all relations in one shot.

  • Batch deleting
  • Foreign keys actions emulation (CASCADE, RESTRICT)
  • Events supports
  • Composite keys supports
  • Transaction supports
  • Unit tested

Requirements

Tested on Yii 1.1.10

Usage

We have 3 models.
User HAS MANY Comment.
User HAS MANY Like.
Comment HAS MANY Like.

// User model
public function behaviors()
{
	return CMap::mergeArray(parent::behaviors(), array(
		 'deletable' => array(
			 'class' => 'ext.deletable-behavior.DeletableBehavior',
			 'relations' => array(
				 'comments' => DeletableBehavior::CASCADE,
				 'likes'    => DeletableBehavior::CASCADE,
			 )
		 )
	));
}

public function relations()
{
	return array(
	     'comments' => array(self::HAS_MANY, 'Comment', 'user_id'),
             'likes' => array(self::HAS_MANY, 'Like', 'user_id'),
	);
}

// Comment model
public function behaviors()
{
	return CMap::mergeArray(parent::behaviors(), array(
		 'deletable' => array(
			 'class' => 'ext.deletable-behavior.DeletableBehavior',
			 'relations' => array(
				 'likes'    => DeletableBehavior::CASCADE
			 )
		 )
	));
}

public function relations()
{
	return array(
             'likes' => array(self::HAS_MANY, 'Like', 'comment_id'),
	);
}

// Like model
public function behaviors()
{
	return CMap::mergeArray(parent::behaviors(), array(
		 'deletable' => array(
			 'class' => 'ext.deletable-behavior.DeletableBehavior',
		 )
	));
}


// event in User model
public function beforeBatchDelete($event)
{
	$batchIds = $event->sender->getBatchIds();
	foreach ($batchIds as $id)
	{
		// delete avatar img
	}
}


// all related Comments and Likes will be deleted too
User::model()->batchDelete(array(1,2,3,4)); 

Behavior must be enabled for all models, that using batch deleting. I recommend include behavior for all models in parent model "ActiveRecord".

Resources

5 0
12 followers
317 downloads
Yii Version: 1.1
License: MIT
Category: Database
Developed by: fantgeass
Created on: Aug 13, 2012
Last updated: 12 years ago

Downloads

show all

Related Extensions