2017-05-24 4 views
1

私は素早く見ましたが、答えを見つけることができません。Doctrine2 - 新しいものを追加してManyToManyの関連付けを削除するには

/** 
* @Entity 
**/ 

class User 
{ 

    /** 
    * @ManyToMany(targetEntity="Role", inversedBy="users") 
    * @JoinTable(name="user_to_roles") 
    **/ 
    protected $roles; 

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

    public function addRole(Role $role) 
    { 
     $role->addUser($this); 
     $this->roles[] = $role; 
    } 

    public function getRoles() 
    { 
     return $this->roles; 
    } 
} 

と役割:

は、以下のエンティティを取り、ユーザーが多くの役割を持つことができます誰

/** 
* @Entity 
**/ 

class Role 
{ 
    /** 
    * @Id 
    * @Column(type="integer") 
    * @GeneratedValue(strategy="AUTO") 
    **/ 
    protected $id; 

    /** 
    * @ManyToMany(targetEntity="User", mappedBy="roles") 
    **/ 
    protected $users; 

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

    public function addUser(User $user) 
    { 
     $this->users[] = $user; 
    } 

    public function getUsers() 
    { 
     return $this->users; 
    } 
} 

私は参照を取得するユーザーを更新すると、更新などのそう:

$user = $this>entityManager->getReference('App\Entity\User', $id); 
$user->addRole($role); 
$this->entityManager->persist($user); 
$this->entityManager->flush(); 

しかし、これは連続のに対し、私のリレーショナルテーブルに新しいロールを追加します私はちょうど現在の行を更新するか、それを削除して新しい行を作成したい(いずれか簡単な方)。どうすればこれを達成できますか?あなたのエンティティにこの機能を追加する

答えて

1

試してみてください。

function setRoles($roles) { 
    $this->roles = new ArrayCollection($roles); 
} 

そして、あなたはこれを試して更新します。

$user = $this>entityManager->getReference('App\Entity\User', $id); 
$roles = array(); 

// add your roles to the array roles 

$user->setRoles($roles);  
$this->entityManager->persist($user); 
$this->entityManager->flush(); 
+0

はありがとうございます。これは完全に機能しました。 –

+0

あなたを助けてうれしい! @RyanHipkiss –

関連する問題