Symfony and Doctrine ORM – Many to many bidirectional relation

The classes below illustrate a many to many bidirectional relation with Doctrine ORM, Symfony3 and FOSUserBundle.

Entity User

<?php
// src/AppBundle/Entity/User.php

namespace AppBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToMany(targetEntity="UserGroup", inversedBy="users")
     * @ORM\JoinColumn(name="usergroup_id", referencedColumnName="id")
     */
    private $usergroups;

    public function __construct()
    {
        parent::__construct();
        $this->usergroups = new ArrayCollection();
    }
}

Read more “Symfony and Doctrine ORM – Many to many bidirectional relation”