zoukankan      html  css  js  c++  java
  • [Yii Framework] 数据保存时自动插入createTime和updateTime

    在components文件夹下面建立一个文件AutoTimestampBehavior.php,里面的内容为
    <?php
    class AutoTimestampBehavior extends CActiveRecordBehavior {

    /**
    * The field that stores the creation time
    */
    public $createTime = 'creatTime';
    /**
    * The field that stores the modification time
    */
    public $updateTime = 'updateTime';


    public function beforeValidate($on) {
    if ($this->Owner->isNewRecord)
    $this->Owner->{$this->createTime} = new CDbExpression('NOW()');
    else
    $this->Owner->{$this->updateTime} = new CDbExpression('NOW()');

    return true;   
    }
    }
    然后在model里面使用这个行为插件
    public function behaviors(){
    return array(
    'AutoTimestampBehavior' => array(
    'class' => 'application.components.AutoTimestampBehavior',
    //You can optionally set the field name options here
    )
    );
    }

    其实在1.1 version之后,可以直接这样的了
    public function behaviors(){
    return array(
    'CTimestampBehavior' => array(
    'class' => 'zii.behaviors.CTimestampBehavior',
    'createAttribute' => 'create_time_attribute',
    'updateAttribute' => 'update_time_attribute',
    )
    );
    }

    如果model里面已经在使用public function behaviors(),记得要在前面加上parent::behaviors($on);

  • 相关阅读:
    Unity3d之UGUI- Image拦截Button响应事件
    hdu1114Piggy-Bank(完全背包)
    cf455A boredom
    hdu2084数塔(入门级dp)
    小米线刷出现remote: partition table doesn't exist
    km算法
    hdu1069 Girls and Boys
    CF1203C Common Divisors
    魔法部落
    java命令行运行出现找不到或无法加载类
  • 原文地址:https://www.cnblogs.com/davidhhuan/p/1717041.html
Copyright © 2011-2022 走看看