我需要保存属性"created_at“在MySQL格式"yyyy-mm-dd hh:mm:ss",但显示在php格式"d-m-Y”。
它在create scenario中运行良好,但当我更新任何属性并保存时,它会覆盖"created_at“,并在数据库中自动设置为"0000-00-00 00:00:00”。我在模型beforeValidade()和afterFind()中使用了两个函数。
common\models\Oficios.php
public function beforeValidate()
{
if ($this->scenario == self::SCENARIO_CREATE){
$this->created_at = date('Y-m-d H:i:s');
}else {
$this->created_at = $this->created_at;
}
return parent::beforeValidate();
}
public function afterFind ()
{
// convert to display format
$this->created_at = strtotime ($this->created_at);
$this->created_at = date ('d-m-Y', $this->created_at);
parent::afterFind ();
}
发布于 2018-10-18 05:48:23
你可以试试这个:
public function rules()
{
return array(
...
array('created_at','default',
'value'=>date('Y-m-d H:i:s'),
'setOnEmpty'=>false,'on'=>'insert')
);
}
并去掉函数"beforeValidate“
我希望它能对你有所帮助。
发布于 2018-10-19 17:11:18
你总是可以使用行为。这是一种更加干净和先进的方式。您可以控制该模型具有的所有事件。下面是一个例子:
public function behaviors()
{
return [
[
'class' => TimestampBehavior::class,
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'created_at',
'value' => date('Y-m-d H:i:s')
],
[
'class' => AttributeBehavior::class,
'attributes' => [
ActiveRecord::EVENT_AFTER_FIND => 'created_at'
],
'value' => function ($model) {
// Any Format you want
return date('d-m-Y', strtotime($model->created_at));
}
]
];
}
发布于 2018-10-23 17:21:50
如果像使用Yii::$app->formatter->asDate($model->created_at,'d-m-Y')
一样将created_at保存为Unix
https://stackoverflow.com/questions/52863844
复制相似问题