Doctrine2 ManyToMany 不执行侦听器事件
我有以下数据库结构:
User > UserRole < Role
UserId UserRoleId RoleId
Name UserId Name
RoleId
Active
CreationDate
而我的学说2类是这样定义的:
And my doctrine2 classes are defined like this:
/**
* @var Roles
*
* @ORMManyToMany(targetEntity="SecRole")
* @ORMJoinTable(name="SEC_USER_ROLE",
* joinColumns={@ORMJoinColumn(name="SEC_USER_ID", referencedColumnName="SEC_USER_ID")},
* inverseJoinColumns={@ORMJoinColumn(name="SEC_ROLE_ID", referencedColumnName="SEC_ROLE_ID")}
* )
*/
private $userRoles;
public function __construct() {
parent::__construct();
$this->userRoles = new DoctrineCommonCollectionsArrayCollection();
}
public function addSecRole(myEntitySecRole $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();
}
}
除了一件事外,一切正常.没有为 SecUserRole 实体调用生命周期事件!.我的怀疑是,由于 Doctrine 正在为自己添加"新的 SecUserRole 记录,因此它不会为它调用事件.
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.
我在听 prePersist、preUpdate、preDelete.也没有得到新的记录.我试过onFlush,但似乎也没有得到它.
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.
好的,提前致谢林凯
推荐答案
到目前为止,还没有找到最好的方法,但似乎 Doctrine 假设您的连接表将自动生成",因此它假设它没有也不需要超过两个加入键(UserId、RoleId).
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).
我为解决这个问题所做的是停止使用多对多,而是使用与 SecUserRole 表的单对多关系.因此,在 addSecRole 方法内部,我插入了新对象,然后在外部刷新了 EM(如上面的示例).
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).
这似乎是我能做的最好的方法.我从这个 http://www.zendcasts.com/ 那里得到了一个想法,其中有一个专为 ManyToMany 制作的演员表映射.
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
相关文章