1

BjyAuthorize modifies the User entity and provides an addRole() method. This accepts a role object and populates the user_role_linker_table

How is it possible to remove a role once it is added to a user?

The associations are set in User:

/**
     * @var \Doctrine\Common\Collections\Collection
     * @ORM\ManyToMany(targetEntity="Application\Entity\Role")
     * @ORM\JoinTable(name="user_role_linker",
     *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")}
     * )
     */
    protected $roles;

2 Answers2

0

After hours of struggle I came up with the following solution:

$userDetails = $em->getRepository('Application\Entity\UserDetails')->findOneBy(['id' => $data['user-details-id']]);
$user = $userDetails->getUser();

$roleRepo = $em->getRepository('Application\Entity\Role');
$roleResult = $roleRepo->findOneBy(['id' => $id]); //$id is the role to delete
$user->removeRole($roleResult);

$em->merge($user);
$em->flush();

In the User entity I added the method:

    public function removeRole($role)
    {
        return $this->roles->removeElement($role);
    }

Not sure if this is the approach that the authors of BjyAuthorize intended but it works for me...

0

Looks good to me. Just want to add that you should first check if the roles contains that role you want to delete.

Such as this:

public function removeRole($role)
{
    if (!$this->roles->contains($role))
    {
         return;
    }
    $this->roles->removeElement($role);
}
awoyotoyin
  • 792
  • 4
  • 8