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".
Refactoring
I'm in the middle of refactoring this extension.
Any suggestions?
suggestions
Hello ! Here is a suggestion (if not too late ^^) :
BTW, I was about to use your extension to manage the link between some model (lets say News) and the Comment model supplied by the yii-comment extension.
relations() : a News HAS_MANY Comments.
Here, I don't want to change the extension's code. I just want to change my models/News.php code. Unfortunately, I found it impossible impossible with your behavior since it wants the Comment model to have a batchDelete() method or closure.
I may have missed something in the settings of course, and in this case, my bad and sorry...
Otherwise, my suggestion is : don't force the users to set your extension on both sides of the relation. If I delete a News, I want to cascade-delete its comments, so your behavior should work even if I only use it on the news model.
Best regards,
C.B.
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.