Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Soft delete in Yii2.0 framework

Tags:

yii2

I am creating a project using Yii2.0 framework, and I am not getting how to do soft delete in this framework. If I delete any record, Delflag column of that table in the database has to get updated to 1. However in core PHP I know how to do it.

like image 426
Sadia Naseeba Avatar asked Oct 26 '25 12:10

Sadia Naseeba


2 Answers

Yes I found out the solution for my above question: soft delete in Yii2.0 framework.

Just have to go to that xyzcontroller.php under controllers folder, and change the actionDelete() function, set the desired column value to whatever value we want, in my case it is DelFlag='9', and then save the model.

public function actionDelete($id)
{
    $model = $this->findModel($id);
    $model->delFlg = '9';
    $model->save();  // equivalent to $model->update();
    return $this->redirect(['index']);
    // $this->findModel($id)->delete();
}

And then go to search() function in the models folder, for that particular model: searchxyz.php, set delFlag='0' where the results are getting filtered; that'ss all.

like image 102
Sadia Naseeba Avatar answered Oct 29 '25 01:10

Sadia Naseeba


I propose to use this behaviour - https://github.com/yii2tech/ar-softdelete

This extension provides support for so called "soft" deletion of the ActiveRecord, which means record is not deleted from database, but marked with some flag or status, which indicates it is no longer active, instead.

This extension provides [[\yii2tech\ar\softdelete\SoftDeleteBehavior]] ActiveRecord behavior for such solution support in Yii2. You may attach it to your model class in the following way:

use yii\db\ActiveRecord;
use yii2tech\ar\softdelete\SoftDeleteBehavior;

class Item extends ActiveRecord
{
    public function behaviors()
    {
        return [
            'softDeleteBehavior' => [
                'class' => SoftDeleteBehavior::className(),
                'softDeleteAttributeValues' => [
                    'isDeleted' => true
                ],
            ],
        ];
    }
}

There are 2 ways of "soft" delete applying:

  • using softDelete() separated method
  • mutating regular delete() method
like image 29
Bohdan Vorona Avatar answered Oct 29 '25 03:10

Bohdan Vorona