15

What is the method to submit a current timestamp directly on an INSERT or an UPDATE? If I were running regular SQL, I would use the function NOW() for the specific SQL field on submission. How would I do that with CakePHP?

$this->Model->save($this->data)
Brad Koch
  • 19,267
  • 19
  • 110
  • 137
macha
  • 153
  • 1
  • 1
  • 4

3 Answers3

22

In CakePHP, you can include the NOW() function unescaped by using DboSource::expression

$this->data['SomeModel']['your_datetime_field'] = DboSource::expression('NOW()');
$this->Model->save($this->data);

This is the preferred way of including MySQL functions in your saves.

http://api.cakephp.org/2.3/class-DboSource.html#_expression

joshua.paling
  • 13,762
  • 4
  • 45
  • 60
webbiedave
  • 48,414
  • 8
  • 88
  • 101
  • so I would have to manipulate the posted data before saving it. – macha Sep 29 '10 at 16:33
  • 1
    Yes. But it's just adding one more element to the array. Also, if you have fields in your table named `created` and `updated`, cakephp will automatically updated them on `INSERT` and `UPDATE` statements, respectively. However, I prefer adding the element manually. – webbiedave Sep 29 '10 at 16:36
  • Whoops, make the `created` and `modified` – webbiedave Sep 29 '10 at 21:18
  • 1
    Don't downvote in silence. If there's a reason for doing it on an answer this old, please give it. Also don't downvote answers that were correct at the time of writing. Rather, comment that it should be updated and include that info (or directly edit if you possess the privilege). – webbiedave May 03 '12 at 18:32
  • 1
    If you get a E_STRICT error, try calling $this->Model->getDataSource()->expression('NOW()') – Inigo Flores Dec 02 '15 at 19:35
7

if you add the created and modified columns in you table they will be automatically populated with current time stamp. If the case is different - i.e. you want to populate a field which later on you want to modify, probably using the edorian's solution is best.

Nik Chankov
  • 6,049
  • 1
  • 20
  • 30
  • This is the cake way and should be the preferred answer +1. If the OP is asking for a modifiable field, she should be more specific. – benjamin Sep 29 '10 at 22:30
0

You can set timestamp field to auto initialize and auto update

timestampfield TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

http://dev.mysql.com/doc/refman/5.0/en/timestamp.html

Galen
  • 29,976
  • 9
  • 71
  • 89