I have a User object in my Symfony2 / Doctrine2 web application. This user has the last_updated attribute to identify the last time everything has changed. I set this attribute to NOT NULL in my database. So far so good.
I find it good practice to create an SQL trigger in a database that sets this last_updated to NOW() on all INSERT or UPDATE . Therefore, you do not need to take care of this in your application. So what I did, I implemented this trigger in my database.
But if now I create a user in my application
$user = new User(); $em = $this->getDoctrine()->getManager(); $em->persist($user); $em->flush();
I get an error from Symfony:
An exception occurred while executing 'INSERT INTO User (username, ..., last_updated) VALUES (?, ..., ?)' With parameters ["johndoe", ..., null]:
SQLSTATE [23000]: Violation of integrity constraint: 1048 Column 'last_updated' cannot be null
The problem is obvious: Symfony is trying to run the INSERT -statement in the database with the null parameter for last_updated , which is not valid because this attribute may not be null.
I could quickly think of two workarounds:
- A
last_updated would be to exclude the last_updated field from the entity description. Then Symfony will not try to transfer anything to the database for this column, and the trigger will set the corresponding value. But I don't think this is a good way, because as soon as I try to update the db schema ( doctrine:schema:update --force ), I will lose my last_updated -column. - Another workaround: just
$user->setLastUpdated(new \DateTime()) before I persist() and flush() . But this will minimize the advantage of using a trigger in my database so as not to worry about it in my application.
Is there a way to tell Symfony / Doctrine that a trigger is running in my database? If not, (how) can I connect to Symfony / Doctrine to implement the proper workaround?
source share