2011-10-02 34 views
1

我有以下數據庫結構:Doctrine2多對多不執行監聽器事件

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

而且我doctrine2類是這樣定義的:

/** 
* @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。既沒有得到新的記錄。我嘗試過Flush,但它似乎並沒有得到它。

有什麼我失蹤了,我怎麼能解決這個問題?自己做插入?當然,這是一個解決方案,但這也讓我自己也做了這些問題,這是我不想做的事情。

那麼,在此先感謝 KAT LIM

回答

0

到目前爲止,還沒有找到最好的方式,但似乎學說假設你的加入表將「自動生成」則認爲,它並沒有,也不需要多於兩個連接鍵(UserId,RoleId)。

我做了什麼來解決它是停止使用ManyToMany,但使用OneToMany關係到SecUserRole表。因此,在addSecRole方法中,我插入了新對象,然後在外部刷新EM(如上面的示例)。

看來這是我能做的最好的方式。我從http://www.zendcasts.com/得到了這個想法,其中有一個專門爲ManyToMany映射投射。

那麼,希望這對所有人都有幫助