How can I make an entity store a createdAt and updatedAt field with doctrine2 mapped by annotation? ... My entity is User. I am 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 am using easyadminbundle to manage the backend.
As you have been told, you can use trigger, but this generates dependency on the database, and in most projects where an ORM is used, it is not desirable.
What you want to do can be done with
lifecyclecallbacks
thedoctrine
. It is very simple.Assuming you have the entity mapped to
Annotations
, it would look like this:And inside this class we create a method that will be called in the events that we configure, for this case, it will be valid with the events
PrePersist
andPreUpdate
Seeing what you use
mysql
for the database, in the case of the fieldcreatedAt
, if you want to be updated with the current date when inserting a user, you can use a trigger like this:But in the case of the field
updatedAt
you do not need to make a trigger since you can set it by default when creating the field, usingNavicat
, in this way:In other words, selecting the field in your case
updatedAt
and then selecting the option belowOn Update Current_Timestamp