Doctrine 2.1 - datetime column default value

前端 未结 7 1219
小蘑菇
小蘑菇 2020-12-30 18:51

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());
         


        
相关标签:
7条回答
  • 2020-12-30 19:08

    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'
    ...
    
    0 讨论(0)
  • 2020-12-30 19:10
    @var string @ORM\Column(name="login_at", type="datetime", options={"default" = "CURRENT_TIMESTAMP"})
    

    This will work. Just posting for future ref.

    0 讨论(0)
  • 2020-12-30 19:11

    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.

    0 讨论(0)
  • 2020-12-30 19:17

    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.

    0 讨论(0)
  • 2020-12-30 19:18

    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.

    0 讨论(0)
  • 2020-12-30 19:29

    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;
    
    0 讨论(0)
提交回复
热议问题