Yii2 在行为中处理 beforesave 事件

Yii2 handle beforesave event in behaviour

我尝试使用 yii2 框架开发应用程序,我使用 beforeSave 事件来处理带有 time() 函数的 createdAt 和 updatedAt,此方法是:

public function beforeSave($insert)
{
    if ($insert) {
        $this->createdAt = time();
    }

    $this->updatedAt = time();

    return parent::beforeSave($insert);
}

我只是想将此方法移动到行为并将其附加到我的模型,我创建了行为 class 并将行为附加到模型但是它不起作用并将 null 传递给数据库,我的行为 class 是:

namespace app\modules\imdb\behaviors;

use yii\base\Behavior;
use yii\db\ActiveRecord;

class saveTimeBehavior extends Behavior
{

   public function events()
   {
       return [
           ActiveRecord::EVENT_BEFORE_INSERT => 'beforeSave',
       ];
   }


   public function beforeSave($event)
   {
       if ($event) {
          $this->createdAt = time();
       }

       $this->updatedAt = time();

       return parent::beforeSave($event);
   }
}

我模型中的附加代码是:

public function behaviors()
{
    return [
        saveTimeBehavior::className(),
    ];
}

请帮助我以正确的方式处理这个问题,非常感谢:)

你可以通过一种简单的方式做到这一点,在创建 table 时,将 created_atupdated_at 的类型识别为 timestamp,它将是添加新记录或更新现有记录时自动填充数据库。

示例:

     'created_at'=> $this->timestamp(),
     'updated_at'=> $this->timestamp(),

注意:您可以使用以下 link 找到有关创建 table 的更多信息:Yii2 Migration

您可以使用 TimeStampBehavior 执行此操作。如果您已将列 (created_at, updated_at) 声明为 int(11) 表示 UNIX timestamp.

use yii\behaviors\TimestampBehavior;

public function behaviors()
{
    return [
        TimestampBehavior::className(),
    ];
}

但是由于您的属性名称不同或者您想使用不同的方式来计算时间戳,您可以像下面这样配置 $createdAtAttribute, $updatedAtAttribute and $value 属性:

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

public function behaviors()
{
    return [
        [
            'class' => TimestampBehavior::className(),
            'createdAtAttribute' => 'createdAt',
            'updatedAtAttribute' => 'updatedAt',
            'value' => new Expression('NOW()'),
        ],
    ];
}