Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic values for updated_at, created_at in Doctrine

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

In Ruby on Rails models there are 2 fields: updated_at and created_at.

Description can be found here: http://guides.rubyonrails.org/migrations.html#migration-overview:

The timestamps macro adds two columns, created_at and updated_at. These special columns are automatically managed by Active Record if they exist.

Can I enable similar functionality in Doctrine 2?

like image 316
Dmitry Avatar asked Jun 26 '13 13:06

Dmitry


1 Answers

  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

like image 87
oroshnivskyy Avatar answered Sep 20 '22 15:09

oroshnivskyy