Automatic values for updated_at, created_at in Doctrine

Dmitry picture Dmitry · Jun 26, 2013 · Viewed 53.3k times · Source

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?

Answer

oroshnivskyy picture oroshnivskyy · Jun 26, 2013
  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