How to implement logical deletion in CakePHP2

Sep 3, 2020 PHP CakePHP cakephp2

#What is logical deletion? Logical deletion means that when the user sees it in a browser, it looks like it is being deleted, but the actual data is stored in a column prepared separately. Therefore, it is possible to restore deleted data from the administrator side.

#What is physical deletion? Delete the data in the database as well. Data cannot be recovered. This is the deletion method using the normal delete method.

#Explanation Download and install SoftDeleteBehavior.

https://github.com/CakeDC/utils/blob/master/Model/Behavior/SoftDeleteBehavior.php

Place the downloaded file in the app / Model / Behavior folder.

#Create a column for logical deletion in the table Delete flag Name: deleted Type: tinyint (1)

Delete date Name: deleted_date Type: datetime

Set the deleted column to 0 by default in the DB When the delete function is executed, it should be implemented so that 1 stands in the deleted column.

#Call the model you want to logically delete as follows


class Model name you want to use extends AppModel {
    // Behavior for logical deletion
    public $ actsAs = array ('SoftDelete');

Describe as follows in #AppModel.


class AppModel extends Model {

    public function exists ($ id = null) {
        if ($ this-> Behaviors-> loaded ('SoftDelete')) {
            return $ this-> existsAndNotDeleted ($ id);
        } else {
            return parent :: exists ($ id);
        }
    }

    public function delete ($ id = null, $ cascade = true) {
        $ result = parent :: delete ($ id, $ cascade);
        if ($ result === false && $ this-> Behaviors-> enabled ('SoftDelete')) {
            return (bool) $ this-> field ('deleted', array ('deleted' => 1));
        }
        return $ result;
    }
}

The above delete () is overwritten by softdelete, and it is in the form of update instead of deleting. Also, if there is a column name deleted, 1 will be set there.

#Controller looks like this


  public function delete ($ id) {
    $ this-> autoRender = false;
    if ($ this-> request-> is ('get')) {
      throw new MethodNotAllowedException ();
    }
    
    if ($ this-> User-> delete ($ id)) {
      $ this-> Session-> setFlash ('Delete!');
      $ this-> redirect (array ('action'=>' index'));
    } else {
      debug (__LINE__);
    }
  }

Yes, this is all right.