Doctrine2 - 如何在添加新的关联时删除ManyToMany关联

时间:2017-05-24 06:41:09

标签: doctrine-orm entity entitymanager

我快速查看但找不到答案。

采取以下实体,即可以担任多种角色的用户:

/**
* @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 个答案:

答案 0 :(得分: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();