Free Android CakePHP GMaps Articles by Bali Web Design

May 25, 2011

Saving Mysql Function Now on Cakephp

Filed under: cakephp,php — admin @ 3:45 am

I think many cakephp programmer will get confuse when they want to save column/field on table with mysql function such as NOW(), CURDATE(), etc, We cannot use simple way of the saveField method or save method on model object.

This code will not save the data field into current date time on mysql.

$this->ModelName->saveField('date_field', 'NOW()');

or

$data['ModelName']['id'] = 1;
$data['ModelName']['date_field'] = 'NOW()';
$this->ModelName->save($data);

It will not work as you want. Because cakephp will ada quote on the value.

So the solution is by using DboSource class. Here are the code look like to save table column with current data time on mysql.

$this->ModelName->saveField('date_field', DboSource::expression('NOW()'));

or

$data['ModelName']['id'] = 1;
$data['ModelName']['date_field'] = DboSource::expression('NOW()');
$this->ModelName->save($data);

I hope this article help you for saving mysql function now, curdate, etc on cakephp model object.


2 Comments »

  1. This doesn’t work somehow, I get “Class ‘DboSource’ not found” fatal error, dont even know why exactly.

    Comment by Damn — June 25, 2012 @ 7:29 pm

  2. And expression is not a static method i 2.1.3

    Comment by Damn — June 25, 2012 @ 7:31 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment