1
votes

I have a User entity and I want to update its 'updated' datetime field everytime an association is set/added/created/edited/removed (be it OneToOne or OneToMany). Basically I want to know when something related to the user has changed in my application.

On top of that, is it recommended to always add association by calling ->addXXX($xxx) from the user entity and cascade persist it? In some parts of my application I set the user from the other side of the relationship, and when using Symfony2 forms it does it that way automatically (I think?).

What would be the best approach? Manually doing it in every method of associated entities that set the user would be overkill.

1
After StayTrase answer, look also at this one : stackoverflow.com/a/16722568/4074148, there is another solution explained. - Veve

1 Answers

2
votes

I think it's not possible to do automatically via general doctrine2 or raw SQL mechanisms. Doctrine2 even not always loading all related entities for performance (see Lazy Loading)

The best way I can suggest is to implement EntityListener for your related entities you want not monitor. Using the postUpdate handler you should be able to explicitly change the timestamp field of parent entity.

I.e child class

/** @Entity @EntityListeners({"ChildListener"}) */
class Child
{
  /** @var User */
  private $parent;

  public function getParent() {return $this->parent; }
}

And the listener itself

class ChildListener
{

  public function postUpdate(Child $child, LifecycleEventArgs $event)
  {
      $child->getParent()->updateTimestamp();
  }
}