Automatic values for updated_at, created_at in Doctrine

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

    You can implement it as a trait as well - like this:

    createdAt ?? new DateTime();
        }
    
        /**
         * @param DateTimeInterface $createdAt
         * @return $this
         */
        public function setCreatedAt(DateTimeInterface $createdAt): self
        {
            $this->createdAt = $createdAt;
    
            return $this;
        }
    
        /**
         * @return DateTimeInterface|null
         */
        public function getUpdatedAt(): ?DateTimeInterface
        {
            return $this->updatedAt ?? new DateTime();
        }
    
        /**
         * @param DateTimeInterface $updatedAt
         * @return $this
         */
        public function setUpdatedAt(DateTimeInterface $updatedAt): self
        {
            $this->updatedAt = $updatedAt;
    
            return $this;
        }
    
        /**
         * @ORM\PrePersist()
         * @ORM\PreUpdate()
         */
        public function updateTimestamps(): void
        {
            $now = new DateTime();
            $this->setUpdatedAt($now);
            if ($this->getId() === null) {
                $this->setCreatedAt($now);
            }
        }
    }
    

    Add this trait to your entity (and don't forget @ORM\HasLifecycleCallbacks() notation):

提交回复
热议问题