Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set CURRENT_TIMESTAMP as default value by the database (i.e. not by PHP)?

After looking around for a while, I still couldn't find a way to get CURRENT_TIMESTAMP inserted by the database server (as default value on INSERT).

The problem: When you persist an object to the database, missing fields are explicitly set to NULL by Doctrine. So it looks like, setting a default value in the table definition, doesn't have any effect at all :-(

I don't want to set the time through PHP (e.g. $object->setTimestamp(new \DateTime());) cause this might return a different time than what the database server has, as explained here: https://stackoverflow.com/a/3705090/1668200

What I've tried so far:

  • Send in NOW literally (e.g. $object->setTimestamp('NOW()');), as explained here: https://stackoverflow.com/a/13850741/1668200
    => Didn't work: Error: Call to a member function format() on string

  • Removing the 'timestamp' property from the object just before persisting it (see https://stackoverflow.com/a/3600758/1668200 ) didn't work either: The field was set to NULL by Doctrine anyway.

Any other solution I found (including the Doctrine extension 'Timestampable' https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/timestampable.md ) uses PHP's time.

like image 776
Thomas Landauer Avatar asked Sep 06 '25 03:09

Thomas Landauer


1 Answers

/**
 * @ORM\Column(type="datetime", options={"default": "CURRENT_TIMESTAMP"})
 */
protected $created;     

Just remember that this will not allow previous rows to be empty if you update an existing table.

like image 103
Jørgen Rudolph Låker Avatar answered Sep 08 '25 16:09

Jørgen Rudolph Låker