LoginSignup
16
16

More than 5 years have passed since last update.

cakePHP CakeDCのsoftDelete

Last updated at Posted at 2015-08-03

cakePHPにおいてfindやadd,view,deleteといったものはデフォルトで用意されていますが、deleteについては、delete_flagやdeletedやisDeleteといった削除フラグ的なもので物理削除ではなく論理削除をしたいところです。

単純にdeleteの代わりを用意してdelete SQLではなくupdate SQLを実行するように書けばわかりやすいかと思います。ですがその場合は、find出の検索時もいちいち削除フラグがonではない(削除されていない)という条件を付けなければなりません。まあ、それだけなのですが。。

せっかくcakePHPやっているのでdeleteの動きを変更してやることができるので使ってみましょう。
behaviorの機能を使うことになります。

CakeDCというところから出ているsoftDeleteというbehaviorを利用します。
Utils Plugin for CakePHP http://cakedc.com

説明にありますが、appModelにそれぞれ追加が必要です。
※検索しててもappModelに追加する記述がなくてうまくいきませんでした。追加するとばっちりです。

あとは、
http://www.tailtension.com/cakephp/398/
こちらが参考になります。

  • テーブルに論理削除用のカラムを作成

削除フラグ

名前:deleted
型:tinyint(1)
※デフォルト値:0

削除日

名前:deleted_date
型:datetime

  • モデルに追加
model/hogehoge.php
public $actsAs = array( 'SoftDelete' );

以下説明です。

SoftDelete Behavior

The SoftDelete behavior allows you to keep records on database and do not show them to users having a "deleted" flag. By default you should have "deleted" and "deleted_date" fields on your database table.
Since "exists" method in Model disable callbacks you may experience problems using it. To avoid these problems you can use the "existsAndNotDeleted" method from the behavior and we provide the following code to be put into AppModel to make this transparent:

AppModel.php
 <?php
public function exists($id = null) {
    if ($this->Behaviors->attached('SoftDelete')) {
        return $this->existsAndNotDeleted($id);
    } else {
        return parent::exists($id);
    }
}

It will call SoftDelete::existsAndNotDeleted() for models that use SoftDelete Behavior and Model:exists for models that do not use it
When deleting an item the SoftDelete behavior will override the delete() and update the record instead. This means that the response to the delete() will be false. In order to override this and return true, you will need to include the following in your AppModel.php file.

AppModel.php
<?php
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;
}
16
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
16