Doctrine: Set CURRENT_TIMESTAMP as default value by the database (i.e. not by PHP)

12,364

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.

Share:
12,364
Thomas Landauer
Author by

Thomas Landauer

See https://www.landauer.at/

Updated on June 05, 2022

Comments

  • Thomas Landauer
    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/1668200

    What I've tried so far:

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