Yii2 表單=>資料庫時間戳存取轉換
阿新 • • 發佈:2018-12-30
- 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;
}
}
}
}