Skip to content

Instantly share code, notes, and snippets.

@exileed
Created August 8, 2017 21:36
Show Gist options
  • Save exileed/0924fd3b947c726b6f427224668a3f00 to your computer and use it in GitHub Desktop.
Save exileed/0924fd3b947c726b6f427224668a3f00 to your computer and use it in GitHub Desktop.
Soft delete behavior for Yii2 ActiveRecord
<?php
namespace app\traits;
/**
* Soft delete behavior for Yii2 ActiveRecord
*
* @property-read bool $isDeleted
*/
trait SoftDelete
{
/**
* Do not delete
* @var bool
*/
public static $softDelete = true;
/**
* Soft delete attribute
* @var string
*/
public static $softDeleteAttribute = 'deleted_at';
/**
* Returns newly created ActiveQuery instance
* @return \yii\db\ActiveQuery
*/
public static function find()
{
$query = parent::find();
// Skip deleted items
if (static::$softDelete) {
$query->andWhere([static::tableName() . '.' . static::$softDeleteAttribute => null]);
}
return $query;
}
/**
* Deletes an ActiveRecord without considering transaction
* @return integer|false the number of rows deleted, or false if the deletion is unsuccessful for some reason
*/
protected function deleteInternal()
{
// Mark as deleted
if (static::$softDelete) {
$this->remove();
$result = 1;
}
// Real delete
else {
$result = parent::deleteInternal();
}
return $result;
}
/**
* Remove (aka soft-delete) record
*/
public function remove()
{
// Evaluate timestamp and set attribute
$timestamp = date('Y:m:d H:i:s');
$attribute = static::$softDeleteAttribute;
$this->$attribute = $timestamp;
// Save record
$this->save(false, [$attribute]);
// Trigger after delete
$this->afterDelete();
}
/**
* Restore soft-deleted record
*/
public function restore()
{
// Mark attribute as null
$attribute = static::$softDeleteAttribute;
$this->$attribute = null;
// Save record
$this->save(false, [$attribute]);
}
/**
* Delete record from database regardless of the $softDelete attribute
*/
public function forceDelete()
{
$softDelete = static::$softDelete;
static::$softDelete = false;
$this->delete();
static::$softDelete = $softDelete;
}
/**
* Returns if property is soft-deleted
* @return bool
*/
public function getIsDeleted()
{
$attribute = static::$softDeleteAttribute;
$idDeleted = $this->$attribute !== null;
return $idDeleted;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment