{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; } }