Zend MantToMany

ManyToMany Relationship: Users ↔ Groups

  • A User can have many Roles
  • A Role can be assigned to many Users

Step-by-Step Demo (Zend + Doctrine)

1. Inject EntityManager in Controller

Inject EntityManager link


2. Create User Entity (module\Application\src\Entity\User.php)

namespace Application\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity
 * @ORM\Table(name="users")
 */
class User
{
    /** @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */
    private $id;

    /** @ORM\Column(type="string") */
    private $name;

     /**
     * @ORM\ManyToMany(targetEntity="Role", inversedBy="users", cascade={"persist"})
     * @ORM\JoinTable(name="user_roles",
     *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")}
     * )
     */
    private $roles;
    public function __construct() {
        $this->roles = new ArrayCollection();
    }

    // Getters and Setters
    public function getId(): ?int { return $this->id; }
    public function getName(): ?string { return $this->name; }
    public function setName(string $name): self { $this->name = $name; return $this; }
    public function getRoles() { return $this->roles; }
    public function addRole(Role $role): self {
        if (!$this->roles->contains($role)) {
            $this->roles[] = $role;
            $role->addUser($this);
        }
        return $this;
    }
}


3. Create Role Entity (module\Application\src\Entity\Role.php)

namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity
 * @ORM\Table(name="roles")
 */
class Role
{
    /** @ORM\Id @ORM\GeneratedValue @ORM\Column(type="integer") */
    private $id;

    /** @ORM\Column(type="string") */
    private $name;

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

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

    // Getters & Setters
    public function getId(): ?int { return $this->id; }
    public function getName(): ?string { return $this->name; }
    public function setName(string $name): self { $this->name = $name; return $this; }

    public function getUsers() { return $this->users; }
    public function addUser(User $user): self {
        if (!$this->users->contains($user)) {
            $this->users[] = $user;
        }
        return $this;
    }
}


4. Generate Migration

Run this in terminal:

php vendor/bin/doctrine-migrations diff


5. Run Migration

php vendor/bin/doctrine-migrations migrate


This will create:

  • users
  • roles
  • user_roles (pivot table automatically)



Create a User with Roles

$user = new User();
$user->setName('Sathish');

$adminRole = new Role();
$adminRole->setName('Admin');

$editorRole = new Role();
$editorRole->setName('Editor');

$user->addRole($adminRole);
$user->addRole($editorRole);

$entityManager->persist($user);
$entityManager->flush();



Read User with Roles

$user = $entityManager->getRepository(User::class)->find(1);

echo "User: " . $user->getName() . "<br>";
foreach ($user->getRoles() as $role) {
  echo "Role: " . $role->getName() . "<br>";
}

Assign Existing Role to User

$user = $entityManager->getRepository(User::class)->find(2);
$role = $entityManager->getRepository(Role::class)->find(1);

$user->addRole($role);

$entityManager->flush();

Remove Role from User

$user = $entityManager->getRepository(User::class)->find(2);
$role = $entityManager->getRepository(Role::class)->find(1);

if ($user->getRoles()->contains($role)) {
  $user->getRoles()->removeElement($role);
}

$entityManager->flush();



Delete a Role

$role = $entityManager->getRepository(Role::class)->find(1);
$entityManager->remove($role);
$entityManager->flush();

Optional: Repository DQL to Join for eager loading

$usersWithRoles = $entityManager->createQuery(
  'SELECT u, r FROM Application\Entity\User u JOIN u.roles r'
)->getResult();



Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.