Search code examples
phpdoctrine-orm

Doctrine 2.1 - datetime column default value


Could someone tell me how to add the default value on a DateTime column? I can't do it like this:

protected $registration_date = date("Y-m-d H:i:s", time());

So how can I handle it?


Solution

  • You map your property as DateTime type then set the value in the constructor using a new DateTime instance:

    /**
     * @Entity
     * @Table(name="...")
     */
    class MyEntity
    {
        /** @Column(type="datetime") */
        protected $registration_date;
    
        public function __construct()
        {
            $this->registration_date = new DateTime(); 
        }
    }
    

    This works as the constructor of a persisted class is not called upon hydration.