Can ActiveRecord just leave timestamp field alone?

As the title. Can ActiveRecord just leave timestamp field alone?

I have created my table like this:




create table oc_schedule_bill (

	id int not null auto_increment,

	update_at timestamp default CURRENT_TIMESTAMP,

	PRIMARY KEY  (id)

) ;



The update_at field will be filled by MySQL.

But now, when i call


model->save()

, The ActiveRecord fill ‘null’ into the field ‘update_at’, which will cause sql error on some version of mysql-server( mysql 5.6.24 on Ubuntu 12.04) .

There is some method to solve this problem, but, obviously, the most elegant way is “just not fill the field update_at”. That is to say, make the field ‘update_at’ read-only, none-writable.

Is there official way to do this?

I believe if you take all rules out for updated_at it should leave it alone. However, you should always set it yourself to have more control over the actual date and/or time stored.

I’m providing two ways to insert a date but this obviously won’t leave it empty like you want;

You can use the built in yii2 time stamp behavior in your model.




use yii\db\Expression;


public function behaviors()

{

	return [

    	[

        	'class' => TimestampBehavior::className(),

        	'updatedAtAttribute' => 'update_at',

        	'value' => new Expression('NOW()'),

    	],

	];

}



This will set the update_at to the current server time however, this will also do it on both create and update but so does yours by having default tmestamp in your DB for the update_at field.

You can also set it in the beforeSave() event manually in your model. This will allow you to only do it on update and not create like the behavior does by default.




use yii\db\Expression;


public function beforeSave($insert)

{

	if (parent::beforeSave($insert)) {

 			//create code

            return true;

	} else {

            $this->update_at =new Expression('NOW()');

        	return false;

	}

}