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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_16885135/article/details/78780457
  • 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;

            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_16885135/article/details/78780457