Skip to content

Instantly share code, notes, and snippets.

@caddoo
Created October 31, 2012 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caddoo/3987996 to your computer and use it in GitHub Desktop.
Save caddoo/3987996 to your computer and use it in GitHub Desktop.
Soft Delete
<?php
/**
* Modify normal delete behaviour so that deletes are handled depending
* on if they have a column called 'deleted' or not
* Cascade deletes all HAS_MANY relations as well
*
* @access public
* @return boolean
*/
public function beforeDelete()
{
$log = new UserActionLog;
$log->action = 'delete';
$log->table_name = $this->tableName();
$log->row_id = $this->id;
foreach ( $this->relations() as $name => $relation ) {
if ( $relation[0] == self::HAS_MANY ) { // If we are dealing with a HAS MANY relation we want to delete all child models
foreach ( $this->{$name} as $relation ) {
$relation->delete();
}
}
}
if ( $this->hasAttribute('deleted') ) {
$this->deleted = 1;
if ( $this->hasAttribute('active') ) {
$this->active = 0;
}
if ( $this->save(false) ) {
$log->save();
}
return false;
} else {
$log->save();
parent::beforeDelete();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment