Doctrine2 ManyToMany doesn't execute listener events

青春壹個敷衍的年華 提交于 2019-12-01 12:39:11

问题


I have the following db structure:

User     > UserRole      < Role
UserId     UserRoleId      RoleId
Name       UserId          Name
           RoleId
           Active
           CreationDate

And my doctrine2 classes are defined like this:

/**
 * @var Roles
 *
 * @ORM\ManyToMany(targetEntity="SecRole")
 * @ORM\JoinTable(name="SEC_USER_ROLE",
 *      joinColumns={@ORM\JoinColumn(name="SEC_USER_ID", referencedColumnName="SEC_USER_ID")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="SEC_ROLE_ID", referencedColumnName="SEC_ROLE_ID")}
 *      )
 */
private $userRoles;

public function __construct() {
  parent::__construct();
  $this->userRoles = new \Doctrine\Common\Collections\ArrayCollection();
}

public function addSecRole(\myEntity\SecRole $role)
{
  $exists = $this->userRoles->exists(function($key, $elem) use($role) {
      return isset($elem) && $elem->getSecRoleCode() == $role->getSecRoleCode();
    });
  return !$exists && $this->userRoles->add($role);
}

To add a new role to the user, I do:

  $r = $rolerep->findOneBySecRoleCode('SystemAdmin');
  $u = $userrep->findOneByUserLogin('sysadmin');
  if (isset($r) && isset($u))
  {
    if ($u->addSecRole($r)) {
      $em->flush();
    }
  }

And everything works fine EXCEPT for one thing. The lifecycle events are not being called for SecUserRole entity!. And my suspicion is that since Doctrine is "adding" the new SecUserRole record for itself, then it doesn't call the events for it.

I'm listening to prePersist, preUpdate, preDelete. Neither get the new record. I tried onFlush, but it seems it doesn't get it either.

Is there something I'm missing, how could I solve this? doing the inserts by myself? Sure that's a solution, but that leaves me to do also the queries myself, which is something I don't want to do.

Well, thanks in advance KAT LIM


回答1:


So far, haven't found the best way BUT seems that Doctrine assumes that your Join Table will be "autogenerated" so it assumes that it doesn't have nor need more than the two joining keys (UserId, RoleId).

What I did to solve it was to stop using a ManyToMany, but use a OneToMany relationship to SecUserRole table. So inside the addSecRole method, I inserted the new object and then flushed the EM on the outside (like the example above).

It seems that's the best way I could do. I got the idea from this http://www.zendcasts.com/ where there is one cast specially for ManyToMany mappings.

Well, hope this helps to all



来源:https://stackoverflow.com/questions/7629635/doctrine2-manytomany-doesnt-execute-listener-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!