LoginSignup
11
9

More than 5 years have passed since last update.

データの登録・更新日の自動挿入

Posted at

cakePHPだと標準でやってくれるテーブルの登録・更新日への自動セット。
標準ではないようなのでひとまずどんな方法があるのか、調べてみました。

その前に、テーブルに以下のフィールド作っておきます。
created
modified

方法その1

beforeSaveをオーバーライド。一番直感的。

user.php

  protected function beforeSave()
    {
            if ($this->hasAttribute('modified'))
            {
                    if ($this->isNewRecord)
                            $this->created = new CDbExpression('NOW()');
                    else
                            $this->modified = new CDbExpression('NOW()');
            }
            return parent::beforeSave();
    }

方法その2

user.php 内にあるrules()を変更する方法。
validationに関連しているところなので、デフォルト値をセットのような
イメージでしょうか。

user.php

  array(
      'created,modified',
            'default',
          'value'=>new CDbExpression('NOW()'),
          'setOnEmpty'=>false,'on'=>'insert'
    ),

いや、変更時も入れてほしいよって時にはこのようにしてみた。
もうちょっとスマートな書き方がありそうですが。

user.php

     array(
        'created',
        'default',
        'value'=>new CDbExpression('NOW()'),
        'setOnEmpty'=>false,
        'on'=>'insert'
     ),
     array(
        'modified',
        'default',
        'value'=>new CDbExpression('NOW()'),
        'setOnEmpty'=>false,
        'on'=>'update'
     ),

方法その3

behaviors()を設定する。
setUpdateOnCreateのイベント時に呼び出されるように設定。

user.php

public function behaviors()
{
    return array(
        'CTimestampBehavior' => array(
            'class' => 'zii.behaviors.CTimestampBehavior',
            'createAttribute' => 'created',
            'updateAttribute' => 'modified',
            'setUpdateOnCreate' => true,
        ),
    );
}

って英語の公式に
http://www.yiiframework.com/wiki/10/how-to-automate-timestamps-in-activerecord-models/
こんな記事がそのまま…!

まだまだYiiを触り始めたばかりですが、みなさんどうぞよろしく!

11
9
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
11
9