Yii Framework Forum: Updating MySQL TIMESTAMP columns - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • This topic is locked

Updating MySQL TIMESTAMP columns Rate Topic: -----

#1 User is offline   Mike 

  • Elite Member
  • PipPipPipPipPip
  • Yii
  • Group: Members
  • Posts: 3,016
  • Joined: 06-October 08
  • Location:Upper Palatinate

Posted 09 December 2008 - 10:03 AM

I usually have a timestamp column in my MySQL tables like this:

changeTime TIMESTAMP NOT NULL


which implicitely declares the column in MySQL with this attributes:
changeTime TIMESTAMP NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP


That means i can update every entry in that table and leave away the changeTime column. It will always be automatically updated to the time of last change. This works even though the column is declared as NOT NULL. MySQL takes care of everything.

With Yii's ActiveRecords i can remove the required rule for that column - that's great. I can create and save a record with NULL in the changeTime attribute and it will have the changeTime set correctly.

But when i load an existing record and save it again, the old value will remain. I have to set changeTime to either null or the current date. Wouldn't it be convenient to somehow declare this column as an autoupdated timestamp column that's set to NULL on every save()?

0

#2 User is offline   Mike 

  • Elite Member
  • PipPipPipPipPip
  • Yii
  • Group: Members
  • Posts: 3,016
  • Joined: 06-October 08
  • Location:Upper Palatinate

Posted 09 December 2008 - 10:34 AM

I've tried to workaround this issue with beforeSave():

public function beforeSave() {
    $this->changeTime=null;
    return true;
}


But now the record doesn't get saved anymore.
0

#3 User is offline   Mike 

  • Elite Member
  • PipPipPipPipPip
  • Yii
  • Group: Members
  • Posts: 3,016
  • Joined: 06-October 08
  • Location:Upper Palatinate

Posted 09 December 2008 - 10:40 AM

Sorry, i tested it with yiic shell and seems like i had to restart the shell session. It works with one minor drawback: after calling save() changeTime is still null. But that's acceptable for me.
0

#4 User is offline   qiang 

  • Yii Project Lead
  • Yii
  • Group: Yii Dev Team
  • Posts: 5,901
  • Joined: 04-October 08
  • Location:DC, USA

Posted 09 December 2008 - 11:47 AM

Yeah, using beforeSave() is probably the best to handle this problem. If you want, you may call CActiveRecord::refresh() to get the up-to-date values.
0

#5 User is offline   Mike 

  • Elite Member
  • PipPipPipPipPip
  • Yii
  • Group: Members
  • Posts: 3,016
  • Joined: 06-October 08
  • Location:Upper Palatinate

Posted 09 December 2008 - 12:02 PM

Ah, ok. Thanks.
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • This topic is locked

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users