Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update `create_at` model attribute only if it is null or blank

I am using YII2 advanced application template with yii2-user.

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

This will set the current timestamp value in my user model. But I want to add this only if it's null; it should not be overwritten if I set the value in my controller.

like image 795
vinod27ece Avatar asked Nov 27 '25 20:11

vinod27ece


1 Answers

You can create your TimestampBehavior with custom logic:

<?php
namespace app\behaviors;

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

class ARTimestampBehavior extends Behavior
{

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

    public function beforeInsert($event)
    {
        $model = $event->sender;
        if ($model->hasAttribute('created_at') && is_null($model->created_at)) {
            $model->created_at = new Expression('NOW()');
        }
        if ($model->hasAttribute('updated_at')) {
            $model->updated_at = new Expression('NOW()');
        }
    }

    public function beforeUpdate($event)
    {
        $model = $event->sender;
        if ($model->hasAttribute('updated_at')) {
            $model->updated_at = new Expression('NOW()');
        }
    }

}

And then use it in your model:

public function behaviors()
{
    return [
        ARTimestampBehavior::className(),
    ];
}
like image 85
stepozer Avatar answered Nov 29 '25 13:11

stepozer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!