How To Exclude Model Attributes From Being Saved

I’m looking for an elegant way of ignoring table columns in the CActiveRecord model. More precisely, the underlying database is MySql and the table “user” uses a timestamp column like this:

[sql]CREATE TABLE user (

user_id INT NOT NULL AUTO_INCREMENT,

ts TIMESTAMP NOT NULL

)

[/sql]

The value of the timestamp column is modified by MySql on every insert (of course) and update which is exactly what I want. However, when the update is performed not via SQL but using the Yii based application, then the timestamp is never updated because the column (as any other column) is considered being part of the CActiveRecord, the current value is read on reading the data and since this field is never changed in the Yii app, it is later written with the same (unchanged) timestamp to the database.

So, MySql would update the timestamp, but because the CActiveRecord includes the column with every update, it is overwritten by the original value. This basically means that the timestamp column is only filled on create but never changes on any further update.

How can I tell the CActiveRecord to exclude this column from being written when the model is saved?

Try this rule:




    array('ts', 'default', 'value'=>null, 'setOnEmpty'=>false),



That will replace ts with null every time before you try to save it, so your timestamp should work correctly.

Ah that’s an interesing idea, thanks a lot for your reply.

Acutally I was looking for a way to completely exclude some columns from the CActiveRecord (from reading and writing), but when I think about it, I find your solution to be equally interesting.

The only thing which I do not exactly like with this is that I would have preferred to make Yii generate a statemente like this:

[sql]update user set first_name=‘afdasfd’, last_name=‘asfdasf’ where user_id=xx;[/sql]

But with your solution, Yii generates:

[sql]update user set first_name=‘afdasfd’, last_name=‘asfdasf’, ts=null where user_id=xx;[/sql]

… which I find sliiiiightly … hm not sooo elegant, since it is actually not generic but solves just the very special problem with MySql timestamp columns. I was dreaming of a way to make Yii really omit the timestamp column from an update statement.

But who am I to criticize a perfectly working solution? ;)