Your Location is: Home > Doctrine-orm

How to create other columns inside the intermediary table of a many-to-many relationship in Symfony?

From: Nauru View: 1883 pheromix 

Question

There are two entities having a many-to-many relationship :

/**
 * @ORM\Entity(repositoryClass=KbFavorisRepository::class)
 */
class KbFavoris
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    ...

    /**
     * @var \Doctrine\Common\Collections\Collection|KbCollection[]
     *
     * @ORM\ManyToMany(targetEntity="KbCollection", mappedBy="kb_favoris",cascade={"persist"})
     */
    protected $collection;

    ...

}

/**
 * @ORM\Entity(repositoryClass=KbCollectionRepository::class)
 */
class KbCollection
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     * @JMS\Groups({"list_collection"})
     */
    private $id;

    ...

    /**
     * @var KbFavoris
     * @ORM\ManyToMany(targetEntity="KbFavoris",inversedBy="collection", cascade={"remove"})
     * @ORM\JoinTable(
     *  name="kb_favoris_collection",
     *  joinColumns={
     *      @ORM\JoinColumn(name="collection_id", referencedColumnName="id")
     *  },
     *  inverseJoinColumns={
     *      @ORM\JoinColumn(name="favoris_id", referencedColumnName="id")
     *  }
     * )
     */
    private $kb_favoris;

    ...

}

How to add another column inside the intermediary table of the many-to-many relationship ?

Best answer

If you want to add some extra fields, you need to create another entity; Ex:

class KbFavoris
{
    // OneToMany here to KbFavorisKbCollection, is array|collection
}

class KbCollection 
{
    // OneToMany here to KbFavorisKbCollection , is array|collection
}

And the new class :

class KbFavorisKbCollection 
{
   // ManyToOne here to KbFavoris (represent one KbFavoris)
   // ManyToOne here to KbCollection (represent one KbCollection )
}