Doctrine: Set CURRENT_TIMESTAMP as default value by the database (i.e. not by PHP)
Solution 1
Have a look at this: https://stackoverflow.com/a/29384596/3255540 it should resolve the problem with Error: Call to a member function format() on string
and force SQL NOW()
to be sent to the database.
Solution 2
/**
* @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.
Comments
-
Thomas Landauer almost 2 years
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/1668200What 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.