views:

83

answers:

3

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)
A: 

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
+1  A: 

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/class/dbo-source#method-DboSourceexpression

webbiedave
so I would have to manipulate the posted data before saving it.
macha
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
Whoops, make the `created` and `modified`
webbiedave
+3  A: 

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
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