Yii2 软删除

什么是软删除

后台操作,删除一条记录,不希望真正的从数据库中删除,用个字段标记一下。比如delete_at。默认0。当执行删除操作,更新delete_at为当前时间戳

这样列表显示的时候只查询delete_at为0的记录。

 

牵涉到Yii2的中的操作

引入SoftDeleteBehavior文件

<?php

namespace common\behavior;

use yii\base\Behavior;
use yii\base\Event;
use yii\db\ActiveRecord;

class SoftDeleteBehavior extends Behavior
{
    /**
     * @var string delete time attribute
     */
    public $timeAttribute = false;
    /**
     *  @var string status attribute
     */
    public $statusAttribute = "is_deleted";
    /**
     *  @var string deleted status attribute
     */
    public $deletedValue = 1;

    /**
     *  @var string active status attribute
     */
    public $activeValue = 0;

    /**
     * @inheritdoc
     */
    public function events() {
        return [
            ActiveRecord::EVENT_BEFORE_DELETE => 'softDelete',
        ];
    }
    /**
     * Set the attribute deleted
     *
     * @param Event $event
     */
    public function softDelete($event) {
        $attributes[1] = $this->statusAttribute;
        $_attribute = $attributes[1];
        if($this->timeAttribute) {
            $this->owner->$_attribute = time();
        } else {
            $this->owner->$attributes[1] = $this->deletedValue;
        }
        // save record
        $this->owner->save(false, $attributes);
        //prevent real delete
        $event->isValid = false;
    }
    /**
     * Restore soft-deleted record
     */
    public function restore() {
        $attributes[1] = $this->statusAttribute;
        $this->owner->$attributes[1] = $this->activeValue;
        // save record
        $this->owner->save(false, $attributes);
    }
    /**
     * Force delete from database
     */
    public function forceDelete() {
        // store model so that we can detach the behavior and delete as normal
        $model = $this->owner;
        $this->detach();
        $model->delete();
    }
}

在需要使用的Model中

use common\behavior\SoftDeleteBehavior;
// ... 
   public function behaviors() {
        return [
            'softDelete' => ['class' => SoftDeleteBehavior::className(),
                'timeAttribute' => true,
                'statusAttribute' => 'deletedAt',
            ],
        ];
    }

Controler中不用改

    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

如果真正删除,就是硬删除。

执行 $this->findModel($id)->forceDelete();

posted @ 2017-09-27 18:35  飞凡123  阅读(2234)  评论(1编辑  收藏  举报