对于$ user-> save()updated_at值将作为时间戳

时间:2017-09-05 07:18:16

标签: mysql yii yii2

这是错误:

Database Exception – yii\db\Exception

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '1504595835' for column 'updated_at' at row 1
The SQL being executed was: UPDATE `user` SET `password_reset_token`='zDPxEMdJ2EaaCf2VsI_Uf9QNf0q2MKcn_1504595835', `updated_at`='1504595835' WHERE `id`=19
Error Info: Array
(
    [0] => 22007
    [1] => 1292
    [2] => Incorrect datetime value: '1504595835' for column 'updated_at' at row 1
)

我不知道为updated_at字段分配了哪个时间戳。

我尝试将updated_at的值设置为date(" Y-m -d H:i:s"),但仍然没有运气。

我也尝试设置行为,但仍然没有运气。

任何人都可以帮忙解决这个问题吗?

4 个答案:

答案 0 :(得分:0)

您已宣布自己的专栏" updated_at"和" created_at"错误。你必须把它改成

int(11) 

here

中所述

答案 1 :(得分:0)

如果要以数字格式保存updated_at,请将数据类型更改为int(11)

或者如果您想以日期时间格式保存,请使用

$model->updated_at = date_format(date_create(), 'Y:m:d: H:i:s')

并将您的数据类型更改为datetime

答案 2 :(得分:0)

首先将dataType更改为表格中的日期时间。

crate ActiveRecord.php in common \ components

<?php
namespace common\components;

use Yii;
use yii\base\Exception;

/**
 * Class ActiveRecord
 * @property string $created_at
 * @property string $updated_at
 * @package common\components
 */
class ActiveRecord extends \yii\db\ActiveRecord {

    public function beforeSave($v){
        if($this->isNewRecord) {
            try {
                $this->created_at = date('Y-m-d H:i:s');
            } catch (Exception $e) {}
        }

        try {
            $this->updated_at=date('Y-m-d H:i:s');
        } catch (Exception $e) {}
        return parent::beforeSave($v);
    }


}

检查 beforeSave 功能 范围ActiveRecord来自common \ components \ ActiveRecord 例如

<?php
namespace common\models;
use common\components\ActiveRecord;
class User extends ActiveRecord implements IdentityInterface
{
    public static function tableName()
    {
        return '{{%user}}';
    }

}

答案 3 :(得分:0)

首先认为created_at和updated_at是由common / models / User模型中的行为管理的,你的数据库表列数据类型应该是&#34; BIGINT&#34;用于保存这些记录。

另一种在&#34; yyyy / mm / dd h中保存updated_at的方法:i:s&#34;您需要删除的格式使用模型行为函数并在更改数据库表列数据类型

后手动保存这些记录