Yii2 表单=>数据库时间戳存取转换

本文介绍了一个Yii2扩展中的时间戳字段自动转换为日期格式的功能实现。通过定义行为(behavior)来自动处理时间戳字段的格式化,确保在保存到数据库前后的正确性和一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • Model
public function behaviors()
{
    $behaviors = parent::behaviors();
    $behaviors['convertTimestamp'] = [
        'class' => ConvertTimestampBehavior::className(),
        'attributes' => [
            static::EVENT_AFTER_FIND    => ['birthday', 'employed_at', 'departure_at'],
            static::EVENT_BEFORE_INSERT => ['birthday', 'employed_at'],
            static::EVENT_BEFORE_UPDATE => ['birthday', 'employed_at', 'departure_at'],
        ],
    ];

    return $behaviors;
}

public function rules()
{
    return [
        ...
        [['birthday', 'employed_at', 'departure_at'], 'date', 'format' => 'php:Y-m-d'],
        ...
    ];
}
  • ConvertTimestampBehavior

use yii\base\Event;
use yii\behaviors\AttributeBehavior;
use yii\db\ActiveRecord;

class ConvertTimestampBehavior extends AttributeBehavior
{
    public $dateFormat = 'Y-m-d';
    /**
     * Evaluates the attribute value and assigns it to the current attributes.
     * @param Event $event
     */
    public function evaluateAttributes($event)
    {
        if ($this->skipUpdateOnClean
            && $event->name == ActiveRecord::EVENT_BEFORE_UPDATE
            && empty($this->owner->dirtyAttributes)
        ) {
            return;
        }

        if (!empty($this->attributes[$event->name])) {
            $attributes = (array) $this->attributes[$event->name];

            foreach ($attributes as $attribute) {

                $value = $this->owner->$attribute;

                if ($event->name == ActiveRecord::EVENT_AFTER_FIND) {
                    if (! is_int($value)) {
                        $value = null;
                    } else {
                        $value = date($this->dateFormat, $value);
                    }
                } else {
                    if (is_int($value)) {
                        continue;
                    }
                    $value = strtotime($value);
                }
                $this->owner->$attribute = $value;

            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值