Doctrine 2.1 - datetime column default value

2019-02-11 11:01发布

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

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

So how?

7条回答
对你真心纯属浪费
2楼-- · 2019-02-11 11:18

Work for me with MySql and Symfony 3.4.

...
fields:
    start_date:
        type: date
        nullable: false
        options:
            default: '1910-01-01'
            comment: 'The default date is 1910-01-01'
...
查看更多
女痞
3楼-- · 2019-02-11 11:20

I think, the best way to accomplish autofill for datetime is to make like that:

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

Putting logic to constructor isn't right solution, because setting default values are SQL client responsibility. If you decide no longer use ORM - you will lost business logic. Plus, if using constructor you won't be able to add default timestamps to datetime attributes for existing rows.

查看更多
姐就是有狂的资本
4楼-- · 2019-02-11 11:20
@var string @ORM\Column(name="login_at", type="datetime", options={"default" = "CURRENT_TIMESTAMP"})

This will work. Just posting for future ref.

查看更多
我只想做你的唯一
5楼-- · 2019-02-11 11:21

There is an extension for this automating this...

https://github.com/l3pp4rd/DoctrineExtensions/blob/master/doc/timestampable.md

/**
     * @var \DateTime
     *
     * @ORM\Column(name="date_added", type="datetime")
     * @Gedmo\Timestampable(on="create")
     */
    private $date_added;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="date_modified", type="datetime")
     * @Gedmo\Timestampable(on="update")
     */
    private $date_modified;
查看更多
虎瘦雄心在
6楼-- · 2019-02-11 11:28

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();
    }
}
查看更多
家丑人穷心不美
7楼-- · 2019-02-11 11:42

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.

查看更多
登录 后发表回答