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();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM