Update one model attribute

Ok…back in the old days of Yii1.1 there was a way to have ActiveRecord modify one attribute without triggering any of the before/after events.

I have a ‘last_login’ in the User model that I get and update during login, then display the old value in a flash message. If I have a timestamp behavior on the User model, how do I change last_login without effecting the modified_at attribute?

Yeah…Found it.


$userModel = User::findOne(['id' => Yii::$app->user->id]);

// Do something with #userModel...

$userModel->updateAttributes(['last_login' => time()]);

Thanks for your consideration.

1 Like

The ‘modified_at’ field has on the database ‘DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP’? If so then you can’t. When it updates the database will set the timestamp of that last update.

What you may end up doing is removing the ‘ON UPDATE’ clause and manually setting that during the save process or setting independent update fields. For instance, my user table has ‘password_updated_on’ and ‘last_login_on’ those are only updated when that specific even happens.

Someone may have a better suggestion, but that’s my thought about it given that you want to update a row without triggering an automatic update for ‘modified_at’.

  • then again, I could totally be misunderstanding what’s being asked for.

The standard user table installed with the ‘init’ command upon initial creation, doesn’t use timestamps. In the model there is the timestamp behavior that basically does the ON UPDATE stuff. I didn’t want the ‘modified_at’ column to be updated every time the User logged in. updateAttributes() apparently goes straight to the db without triggering all the other ActiveRecord stuff. My follow up post works, but thanks for you thoughts.