TimestampBehavior 在 Yii2 中不起作用 [英] TimestampBehavior is not working in Yii2

查看:31
本文介绍了TimestampBehavior 在 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' 字段不会在当前时间更新.这些字段的类型设置为日期时间.请需要您的帮助.

Above code is for my controller behavior function. While creating or updating, 'create_time' and 'update_time' fields are not getting updated by current time. Type of those fields are set to datetime. Please need your help.

推荐答案

你必须在你的模型的行为方法中声明它.

You have to declare it in the behaviors method of your model.

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

To use TimestampBehavior, insert the following code to your ActiveRecord class

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

这篇关于TimestampBehavior 在 Yii2 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆