user2625666
user2625666

Reputation: 31

Understanding Symfony 5 Doctrine ManyToOne relation concepts with Users and Roles

I'm trying to understand Doctrine ORM relationship concepts, because I spent lot of time to create, according to me, a very simple use case, but, I didn't manage to do it because I've got a slack of knowledges...

Here is my issue : I've got 2 entities, UserApp and RoleApp.

I want to have the possibility to manage roles from users threw a database, instead of hardcoding role, in array format, directly into users table. So to do that I've got a classic foreign key role_id into user_app table which references the primary key into role_app table.

I need, for each user, to get his role, and to bring it in the right format expected for Symfony Authentification :


        class UserApp implements UserInterface, \Serializable{
    .....
    /**
     * @var UserRole
     * @ORM\ManyToOne(targetEntity="App\Entity\UserRole")
     * @ORM\JoinColumn(nullable=false)
     *
     */
    private $role;

    public function getUserRole(): array{ // I know it's wrong but I don't know what is the right type to get 

        return $this->role->getUserRole($this);
    }

    /**
     * Returns the roles or permissions granted to the user for security.
     */
    public function getRoles(): array{
    //$role = ["ADMIN_USER"];
    $role = $this->getUserRole();
    dump($role);

    return array_unique($role);


class UserRole{
    /**
     * @ORM\Column(type="json")
     */
    private $appRole = [];

    public function getUserRole(UserApp $user): ?array
    {
        $userRoleRepository = new UserRoleRepository();
        $userRole[] = $userRoleRepository->find(1);
        dump($userRole);
        return $userRole;
    }

}

But this code doesn't provide the right format for user's role need for Symfony authentification :(

Upvotes: 1

Views: 196

Answers (1)

user2625666
user2625666

Reputation: 31

Finaly I managed to do what I want; here is my solution, I hope it can help...

   class UserApp implements UserInterface, \Serializable
   {
  ....
      /**
     * @var UserRole
     * @ORM\ManyToOne(targetEntity="App\Entity\UserRole")
     * @ORM\JoinColumn(nullable=false)
     *
     */
    private $role;

    public function getUserRole(): UserRole
    {
        return $this->role->getRoleUser($this);
    }

    /**
     * Returns the roles or permissions granted to the user for security.
     * it's for authentification compliance
     */
    public function getRoles(): array
    {
        $arrRole = $this->getUserRole()->getAppRole();
        return array_unique($arrRole);
    }

    ......

    class UserRole{

    .....
    /**
     * @ORM\Column(type="json")
     */
    private $appRole = [];//For authentification compliance

    .....
   public function getRoleUser(UserApp $user): ?self
    {
        return $this;
    }`enter code here`

Upvotes: 1

Related Questions