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

来源:互联网 发布:ubuntu top命令详解 编辑:程序博客网 时间:2024/06/07 10:50
  • 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;            }        }    }}
原创粉丝点击