wuliao 2016-03-13 22:07:55 6808次浏览 2条评论 6 2 0

看到过有人提供了一种用beforeSave 的方法实现 但是不够优雅
也看见有人提出用behavior的方式 但是只是最简单的实现方式 只能保存时间戳
现在我介绍的方式是可以直接格式化时间戳后保存的 废话不多说 直接上代码

namespace common\behaviors;
use Yii;
use yii\base\Behavior;
use yii\db\BaseActiveRecord;

/**
 * @author Skilly
 */
class SaveBehavior extends Behavior
{
    
    public $createdAttribute = 'created';

    public $updatedAttribute = 'updated';

    public $attributes = [];

    private $_map;

    public function init()
    {
        if (empty($this->attributes)) {
            $this->attributes = [
                BaseActiveRecord::EVENT_BEFORE_INSERT => [$this->createdAttribute, $this->updatedAttribute],//准备数据 在插入之前更新created和updated两个字段
                BaseActiveRecord::EVENT_BEFORE_UPDATE => [$this->updatedAttribute]// 在更新之前更新updated字段
            ];
        }

        $this->_map = [
            $this->createdAttribute => time(),//在这里你可以随意格式化
            $this->updatedAttribute => time(),
        ];
    }

    //@see http://www.yiichina.com/doc/api/2.0/yii-base-behavior#events()-detail 
    public function events()
    {
        return array_fill_keys(array_keys($this->attributes), 'evaluateAttributes');
    }
    
    public function evaluateAttributes($event)
    {
        if (!empty($this->attributes[$event->name])) {
            $attributes = $this->attributes[$event->name];
            foreach ($attributes as $attribute) {
                if (array_key_exists($attribute, $this->owner->attributes)) {
                    $this->owner->$attribute = $this->getValue($attribute);
                }
            }
        }
    }

    protected function getValue($attribute)
    {
       return $this->_map[$attribute];
    }
}
        /**
	 * 行为
	 */
	public function behaviors()
	{
		return [
                      // AR模型的 插入/更新 前的行为,将会自动填充 created, updated 等字段
                      \common\behaviors\SaveBehavior::className()
               ]; 
	}

以上

觉得很赞
  • 评论于 2016-03-15 10:37 举报

    不错。不过这个功能本身就有的。。。yii\behaviors\TimestampBehavior

    1 条回复
    评论于 2016-03-15 18:20 回复

    非常感谢 又知道了一个方法

  • 评论于 2016-04-01 11:21 举报

    可以在具体说说你这方法吗???我还是看不懂

您需要登录后才可以评论。登录 | 立即注册