TimestampBehavior在Yii2中不起作用

时间:2014-11-02 12:08:14

标签: yii2

public function behaviors()
{
    return [
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'delete' => ['post'],
            ],
        ],

        'access' => [
            'class' => AccessControl::className(),
            'only' => ['create', 'update', 'delete', 'view', 'index'],
            'rules' => [
                // allow authenticated users
                [
                    'allow' => true,
                    'roles' => ['@'],
                ],
                // everything else is denied by default
            ],
        ],

        [
            'class' => TimestampBehavior::className(),
            'attributes' => [
                ActiveRecord::EVENT_BEFORE_INSERT => ['create_time', 'update_time'],
                ActiveRecord::EVENT_BEFORE_UPDATE => ['update_time'],
            ],
        ],
    ];
}

以上代码适用于我的控制器行为功能。在创建或更新时,“create_time”和“update_time”字段不会按当前时间更新。这些字段的类型设置为datetime。请你帮忙。

5 个答案:

答案 0 :(得分:3)

试试这个,它对我有用:

use yii\db\Expression;
...

        [
            'class' => TimestampBehavior::className(),
            'updatedAtAttribute' => 'update_time',
            'value' => new Expression('NOW()'),
        ],

答案 1 :(得分:3)

您必须在模型的行为方法中声明它。

  

要使用TimestampBehavior,请将以下代码插入ActiveRecord类

public function behaviors()
{
  return [
    'class' => TimestampBehavior::className(),
        'attributes' => [
           ActiveRecord::EVENT_BEFORE_INSERT => ['create_time', 'update_time'],
           ActiveRecord::EVENT_BEFORE_UPDATE => ['update_time'],
    ],
  ];
}

答案 2 :(得分:1)

您也可以使用

 'value' => date('Y-m-d H:i:s')

如果您想使用PHP日期时间。

答案 3 :(得分:1)

我使用new Expression('NOW()')来存储当前时间戳。但它不会根据当前时区存储日期。相反,它会根据服务器时间进行存储。

我只是用普通的php日期函数来解决这个问题。

例如:

use yii\behaviors\TimestampBehavior;
use yii\db\Expression;

public function behaviors()
{
    return [
        'timestamp' => [
            'class' => 'yii\behaviors\TimestampBehavior',
            'attributes' => [
                ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
            ],
            'value' => date('Y-m-d H:i:s'),
        ],
    ];
}

答案 4 :(得分:0)

您还必须添加值并使用类Expression

use yii\behaviors\TimestampBehavior;
use yii\db\Expression;

public function behaviors()
{
    return [
        'timestamp' => [
            'class' => 'yii\behaviors\TimestampBehavior',
            'attributes' => [
                ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
            ],
            'value' => new Expression('NOW()'),
        ],
    ];
}