A CakePHP gotcha for migrating from 1.1 to 1.2+ on Model->create()

2 minute read Published:

I reported this as a ticket, but as it turns out, it’s a design choice.. but it’s enough of a gotcha that I thought I should report it.

What happened

The $this->ModelName->create() set the defaults for the next save, which is what I would expect. But on my database there’s a default value set for the ‘created’ field (the standard for datetime columns in PHPmyAdmin) as well as the ‘modified’ and ‘updated’ fields.

So when the $this->ModelName->create() function ran, it populated the ‘created’ and ‘updated’ and ‘modified’ fields based on their default values in MySQL; which is “0000-00-00 00:00:00″.

Subsequently, when I ran $this->ModelName->save($dataWithoutCreated); the ‘created’ and ‘updated’ and ‘modified’ fields were not defaulting to the current timestamp when they were not set by the $data passed into save… since they already had a “valid” value.

The Solution

Of course you can modify your model with a beforeSave() code to strip those off, but the “real” solution recommended by Mark Story is to change the default value of those fields in the database to NULL. This is something that sounded foreign to me, since PHPMyAdmin defaults to “0000-00-00″ for date/time fields, but it seems to work fine and I usually will defer to recommendations of the CakePHP core devs (and usually am happy I’ve done so).

Published by in cakephp using 216 words.

comments powered by Disqus