Search code examples
phpsymfonydoctrinedoctrine-extensionssql-timestamp

How can I get Gedmo\Timestampable to keep updated_at null on first create?


I've got a Symfony 2.8 app which uses The Gedmo\Timestampable annotations for automatic created_at and updated_at operations, but it seems to be putting the same timestamp into the updated_at column when the entity/row is first created. An UPDATE does cause the updated_at column to show a newer timestamp, but I want this to be blank to begin with.

My understanding is that on an INSERT, only the created_at column should be populated with the timestamp and the updated_at should stay blank, because it hasn't been updated as such. Only after the first update of the column should it get the value of the updating time.

Am I correct in expecting this? Is there something wrong with my code/config? Or does this annotation actually set the values for both columns by design?

My config.yml:

...
stof_doctrine_extensions:
    default_locale: "%locale%"
    translation_fallback: true
    orm:
        default:
            translatable: true
            timestampable: true
...

My entity:

...
/**
 * An automatic timestamp of the creation.
 *
 * @var \DateTime $createdAt
 * @Gedmo\Timestampable(on="create")
 * @ORM\Column(name="created_at", type="datetime")
 */
public $createdAt;

/**
 * An automatic timestamp of the updation. 
 *
 * @var \DateTime $updatedAt
 * @Gedmo\Timestampable(on="update")
 * @ORM\Column(name="updated_at", type="datetime")
 */
protected $updatedAt;
...

The table defines the two columns as DATETIME and they have no default clauses.


Solution

  • This is done by design, as we can see if we open the file "vendor/gedmo/doctrine-extensions/lib/Gedmo/Timestampable/Timestampable.php", line 22 (on my version of Gedmo):

    /**                                                                                                                                                                                                                                                                           
     * @gedmo:Timestampable(on="update")                                                                                                                                                                                                                                          
     * dates which should be updated on update and insert                                                                                                                                                                                                                         
     */ 
    

    After all, an INSERT is kinda like an update of the table / record as well. If you need to know whether the object was freshly created or not, you could still perform a check between the date stored in "createdAt" and the one stored in "updatedAt".