在我的数据库中软删除是 字段为deleted_at 类型为 datetime

首先创建 SoftDeleteAtBehavior.php

softDelete();
        $event->isValid = false;
    }

    public function softDelete()
    {
        $attribute = $this->attribute;
        $this->owner->$attribute = $this->getValue(null);
        return $this->owner->save(false, [$attribute]);
    }

    public function unDelete()
    {
        $attribute = $this->attribute;
        $this->owner->$attribute = null;
        return $this->owner->save(false, [$attribute]);
    }

    public function hardDelete()
    {
        $model = $this->owner;
        $this->detach();
        return 0 !== $model->delete();
    }

    protected function getValue($event)
    {
        if ($this->value instanceof Expression) {
            return $this->value;
        } else {
            return $this->value !== null ? call_user_func($this->value, $event) : date('Y-m-d H:i:s');
        }
    }
}

然后再模型文件里引用

public function behaviors()
{
    return [
        [
            'class' => SoftDeleteAtBehavior::className(),
            'attribute' => 'deleted_at',
        ],
    ];
} 

方法说明 softDelete 软删除 unDelete 取消删除 hardDelete 硬删除
这样的话做软删除就可以直接使用softDelete方法例如

public function actionDestroy($id)
{
    if (!($model = $this->modelClass::findOne($id))) {
        return $this->message("找不到数据", $this->redirect(Yii::$app->request->referrer), 'error');
    }

    if ($model->softDelete()) {
        return $this->message("删除成功", $this->redirect(Yii::$app->request->referrer));
    }

    return $this->message("删除失败", $this->redirect(Yii::$app->request->referrer), 'error');
}

这样写的软删除需要在查询语句上增加 deleted_at=>null 的条件,所以我在模型的基类里重构了find 方法

/**
     * @return \yii\db\ActiveQuery
     */
    public static function find()
    {
        return new class(get_called_class()) extends \yii\db\ActiveQuery {
            public function init()
            {
                parent::init();
                $this->andWhere(['deleted_at' => null]);
            }
        };
    }

这样软删除就完成了