Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 284
Jazi Avatar asked Oct 08 '11 17:10

Jazi


People also ask

How do you set the default value of a data field to current datetime value?

Learn MySQL from scratch for Data Science and Analytics We can set the now() function as a default value with the help of dynamic default. First, we will create a table with data type” datetime”. After that, we will set now() as the default value for column “MyTime” as shown below.

What is the default value for datetime in MySQL?

DATETIME has a default of NULL unless defined with the NOT NULL attribute, in which case the default is 0.


3 Answers

For default value CURRENT_TIMESTAMP:

     @ORM\Column(name="created_at", type="datetime", options={"default": "CURRENT_TIMESTAMP"})

Or for older Symfony versions:

     @ORM\Column(name="created_at", type="datetime", options={"default": 0})

Worked for me... However this works only with MySQL.

like image 92
sanis Avatar answered Nov 08 '22 13:11

sanis


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.

like image 38
Max Avatar answered Nov 08 '22 13:11

Max


You can also use lifecycle callbacks if you want to be very precise:

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\HasLifecycleCallbacks
 * ...
 */
class MyEntity
{
    /**
     * @ORM\PrePersist
     */
    public function onPrePersistSetRegistrationDate()
    {
        $this->registration_date = new \DateTime();
    }
}
like image 58
Alessandro Desantis Avatar answered Nov 08 '22 13:11

Alessandro Desantis