| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135 |
- <?php
- namespace addons\OperationCenter\common\models\traits;
- /**
- * 软删除工具类
- * Trait SoftDeleteTrait
- * @package app\common\trait_class
- */
- trait SoftDeleteTrait
- {
- /**
- * @var int 删除默认值
- */
- static $deleteDefault = 0;
- /**
- * 软删除
- * @return mixed
- * @throws \Exception
- */
- public function softDelete()
- {
- $this->{self::getDeletedAtAttribute()} = time();
- $ret = $this->save(false, [self::getDeletedAtAttribute()]);
- $this->afterSoftDelete();
- return $ret;
- }
- public function afterSoftDelete()
- {
- // Default implementation
- }
- /**
- * 软删除
- * @return mixed
- * @throws \Exception
- */
- public function delete()
- {
- return $this->softDelete();
- }
- /**
- * Gets the deleted_at attribute name
- *
- * @throws \Exception
- */
- static public function getDeletedAtAttribute()
- {
- return 'deleted_at';
- }
- /**
- * @return mixed
- * @throws \Exception
- */
- public function restore()
- {
- $this->{self::getDeletedAtAttribute()} = self::$deleteDefault;
- return $this->save(false, [self::getDeletedAtAttribute()]);
- }
- /**
- * 批量删除
- * @param null $condition
- * @param array $params
- * @return mixed
- * @throws \Exception
- */
- public static function deleteAll($condition = null, $params = [])
- {
- $deleteField = self::getDeletedAtAttribute();
- $deleteFieldValue["{$deleteField}"] = time();
- $command = static::getDb()->createCommand();
- $command->update(static::tableName(), $deleteFieldValue, $condition, $params);
- return $command->execute();
- }
- /**
- * 过滤软删除的数据
- * @return \yii\db\ActiveQuery
- * @throws \Exception
- */
- public static function find()
- {
- $deleteField = self::getDeletedAtAttribute();
- $where = [
- static::tableName() . '.' . "{$deleteField}" => self::$deleteDefault
- ];
-
- return parent::find()->andWhere($where);
- }
- /**
- * 查询包含软删除的数据
- * @return \yii\db\ActiveQuery
- * @throws \Exception
- */
- public static function withTrashedFind()
- {
- return parent::find();
- }
- /**
- * 只查询软删除数据
- * @return \yii\db\ActiveQuery
- * @throws \Exception
- */
- public static function onlyTrashedFind()
- {
- $deleteField = self::getDeletedAtAttribute();
- $where = ['not', [$deleteField => self::$deleteDefault]];
- return parent::find()->andWhere($where);
- }
- /**
- * 判断当前实例是否被软删除
- * @return false
- * @throws \Exception
- */
- public function trashed()
- {
- $field = $this->getDeletedAtAttribute();
- $softDelete = $this->$field ?? false;
- if ($field && ($softDelete === self::$deleteDefault)) {
- return false;
- }
- return true;
- }
- }
|