Skip to content

Instantly share code, notes, and snippets.

@uaoleg
Last active March 18, 2020 11:42
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save uaoleg/8a310613de915d8cc89f to your computer and use it in GitHub Desktop.
Save uaoleg/8a310613de915d8cc89f to your computer and use it in GitHub Desktop.
Yii2 ActiveRecord Soft Delete behavior
<?php
namespace common\traits;
/**
* Soft delete behavior for Yii2 ActiveRecord
*
* @copyright (c) 2015, Oleg Poludnenko
* @license https://opensource.org/licenses/MIT MIT
*
* @property-read bool $isDeleted
*/
trait SoftDelete
{
/**
* Do not delete
* @var bool
*/
public static $softDelete = true;
/**
* Soft delete attribute
* @var string
*/
public static $softDeleteAttribute = 'timeDeleted';
/**
* 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;
}
}
@ahmedyaghi
Copy link

ahmedyaghi commented Aug 29, 2017

first of all I would like to thank you
second
If you wrote User::find()->all();
It will return all users without soft deleted users and it's expected
now if i wrote User::find()->where([])->all();
It will return all users with soft deleted users and it's unexpected
could you solve this please

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment