データを削除しないで削除フラグだけたてておきたいときがよくあります。
webアプリを作る場合はコメントなどはこの機能が必須になります。つけとかないとあとでユーザー間のもめごとが起きたときに困ってしまいます。

Symfony&Doctrineならばこの論理削除が簡単にできます。

■準備

  1. Schema.ymlでactAsにSoftDeleteを追加する
    Comment:
      actAs: { SoftDelete: ~ }
      columns:
        comment_id:        { type: integer, primary: true, autoincrement: true}
        user_id:           { type: integer, notnull: true}
        comment:           { type: string, notnull: false}
    
  2. migrateとかbuild:modelとかをして、DBに変更を適用させる
  3. ProjectConfigration.class.phpでconfigureDoctrine関数を追加し、起動時にDoctrineのSoftDeleteの機能が有効になるように設定する
      public function configureDoctrine(Doctrine_Manager $manager)
      {
        $manager->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true);
      }


■つかいかた
この機能を追加する前と何も変わらずに使えます
例)削除済みでないコメントで、特定のユーザーのものを取得する

 $data = CommentTable::getInstance()
              ->createQuery('c')
              ->where('c.user_id = '. $userId)
              ->execute();



■削除済みのデータもとりたいとき
削除済みのデータを取りたいときはwhereでdeleted_atのところに条件を追加するようにしてあげます。
例)削除済みのコメントで、特定のユーザーのものを取得する

 $data = CommentTable::getInstance()
              ->createQuery('c')
              ->where('c.user_id = '. $userId)
              ->addWhere('c.deleted_at is not null')
              ->execute();

削除済みのも削除してないのもとりたいときは、ちょっとスマートじゃないですがwhereで両方指定してあげます
例)削除済みのも含め、すべてのコメントで特定のユーザーのものを取得する

 $data = CommentTable::getInstance()
              ->createQuery('c')
              ->where('c.user_id = '. $userId)
              ->addWhere('c.deleted_at is null or c.deleted_at is not null')
              ->execute();
 

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

*

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>