Automatic values for updated_at, created_at in Doctrine

前端 未结 5 1318
感动是毒
感动是毒 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:08

    1. You can call $this->setCreatedAt(new \DateTime()) in __construct method.
    2. You can use Life Cycle Callbacks
    /**
     * @ORM\PrePersist
     * @ORM\PreUpdate
    */
    public function updatedTimestamps(): void
    {
        $this->setUpdatedAt(new \DateTime('now'));    
        if ($this->getCreatedAt() === null) {
            $this->setCreatedAt(new \DateTime('now'));
        }
    }
    

    And don't forget to add into entity class notation: @ORM\HasLifecycleCallbacks

提交回复
热议问题