Cakephp 2.X Modelの論理削除の実装
自社のサイトを更新していたらブログを全然書いていないことに気付いたのでたまにはメモ書きしようと思います。
今回は、CakePHP2.X系で論理削除を実装する流れです。
何件かbehaviorがあるようですが今回はCakeDCという所のBehaviorを紹介します。
1、まずbehaviorをダウンロードして/Model/Behaviorディレクトリにいれます。(MITライセンス)
https://github.com/CakeDC/utils/blob/master/Model/Behavior/SoftDeleteBehavior.php
2、論理削除する対象のモデルに下記項目を追加する
[php]
  `deleted` tinyint(1) NOT NULL DEFAULT 0,
  `deleted_date` DATETIME  DEFAULT NULL,
[/php]
3、/Model/AppModel.phpに下記関数を記述します。
[php]
public function exists($id = null) {
    if ($this->Behaviors->attached(‘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;
}
[/php]
4、対象となるモデルでSoftDeleteBehaviorの呼び出し
[php]
class Post extends AppModel {
  public $actsAs = array( ‘SoftDelete’ );
[/php]
5、後は自動で論理削除されます。
6、削除されたレコードも表示した場合はdetachします。
[php]
    $this->Behaviors->detach(‘SoftDelete’);
    $posts= $this->Post->find("all", $params);
[/php]
