How can I make an entity store a createdAt and updatedAt field with doctrine2 mapped by annotation? ... My entity is User. I'm using easyadminbundle to manage the backend.
How can I make an entity store a createdAt and updatedAt field with doctrine2 mapped by annotation? ... My entity is User. I'm using easyadminbundle to manage the backend.
As you have been told, you can use trigger, but this generates dependence on the database, and in most projects where an ORM is used is undesirable.
What you want to do can be done with the lifecyclecallbacks
of doctrine
. It's very simple.
Assuming you have the entity mapped with Annotations
, it would be like this:
<?php
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
/**
* @ORM\Entity(repositoryClass="UserRepository")
* @ORM\Table(name="users")
* @ORM\HasLifecycleCallbacks()
*/
class User implements AdvancedUserInterface {
// ...
/**
* @ORM\Column(type="datetime")
*/
private $createAt;
/**
* @ORM\Column(type="datetime")
*/
private $updateAt;
// ...
}
And within this class we create a method that will be called in the events that we configure, for this case, it will be worth with the events PrePersist
and PreUpdate
/**
* @ORM\PrePersist
* @ORM\PreUpdate
*/
public function onSaveAction()
{
if (!$this->getCreationDate()) {
$this->createAt = new DateTime();
}
$this->updateAt = new DateTime();
// Resto de la lógica antes de guardar, puede ser por ejemplo, comprobar un campo
}
Seeing that you use mysql
for the database, for the case of the field createdAt
, if you want to be updated with the current date when inserting a user you can use a trigger like this:
CREATE TRIGGER upd_user BEFORE INSERT ON User
BEGIN
IF NEW.createdAt=null THEN
INSERT INTO User SET NEW.createdAt = CURDATE();
END IF;
END
But for the case of the field updatedAt
you do not need to make a trigger since you can put it by default when creating the field, using Navicat
, like this:
That is, selecting in your case the field updatedAt
and then you select the option below On Update Current_Timestamp