【问题标题】:Doctrine2 ManyToMany doesn't execute listener eventsDoctrine2 ManyToMany 不执行侦听器事件
【发布时间】:2011-11-29 14:05:46
【问题描述】:

我有以下数据库结构:

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

我的学说2类是这样定义的:

/**
 * @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);
}

要向用户添加新角色,我会这样做:

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

除了一件事之外,一切都很好。没有为 SecUserRole 实体调用生命周期事件!。我的怀疑是,由于 Doctrine 正在为自己“添加”新的 SecUserRole 记录,所以它不会为它调用事件。

我正在听 prePersist、preUpdate、preDelete。也没有获得新记录。我试过onFlush,但似乎也没有。

我缺少什么,我该如何解决?自己做插入?当然这是一个解决方案,但这让我自己也做查询,这是我不想做的事情。

好的,提前谢谢 凯特林

【问题讨论】:

    标签: php orm symfony1 doctrine-orm


    【解决方案1】:

    到目前为止,还没有找到最好的方法,但似乎 Doctrine 假定您的联接表将是“自动生成的”,因此它假定它不需要也不需要超过两个联接键(UserId、RoleId)。

    我解决这个问题的方法是停止使用 ManyToMany,而是使用与 SecUserRole 表的 OneToMany 关系。所以在 addSecRole 方法中,我插入了新对象,然后在外部刷新了 EM(如上例)。

    这似乎是我能做的最好的方式。我从这个http://www.zendcasts.com/ 得到了这个想法,其中有一个专门针对多对多映射的演员。

    希望对大家有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-03
      • 2018-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多