Automatic values for updated_at, created_at in Doctrine

前端 未结 5 1333
感动是毒
感动是毒 2021-01-31 07:42

I want to make fields updated_at and created_at in my Doctrine entities to update automatically.

In Ruby on Rails models there

5条回答
  •  终归单人心
    2021-01-31 08:25

    This is another option if you would ever want to handle them separately.

    use Doctrine\ORM\Mapping as ORM;
    
    /**
     * @ORM\Entity
     * @ORM\Table(name="person")
     * @ORM\HasLifecycleCallbacks
     */
    class Person
    {
        ..........
    
        /**
         * @var datetime $created
         *
         * @ORM\Column(type="datetime")
         */
        protected $created;
    
        /**
         * @var datetime $updated
         * 
         * @ORM\Column(type="datetime", nullable = true)
         */
        protected $updated;
    
    
        /**
         * Gets triggered only on insert
    
         * @ORM\PrePersist
         */
        public function onPrePersist()
        {
            $this->created = new \DateTime("now");
        }
    
        /**
         * Gets triggered every time on update
    
         * @ORM\PreUpdate
         */
        public function onPreUpdate()
        {
            $this->updated = new \DateTime("now");
        }
    
        ..........
    }
    

提交回复
热议问题