Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine2 generates two extra tables for a ManyToMany relationship

Problem

I'm setting up a database by using Symfony2 and Doctrine2 (annotation). I followed the examples perfectly (Doctrine2 relationship documentation), but somehow when I update my schema (doctrine:schema:update --force) it creates two additional tables.

My two entities are Article and District, the code is below.

Code

Article entity:

/**
 *
 * @var \Doctrine\Common\Collections\ArrayCollection $districts
 *
 * @ORM\ManyToMany(targetEntity="District", inversedBy="articles")
 * @ORM\JoinTable(name="articles_districts",
 *     joinColumns={@ORM\JoinColumn(name="article_id", referencedColumnName="id")},
 *     inverseJoinColumns={@ORM\JoinColumn(name="district_id", referencedColumnName="id")}
 * )
 */
protected $districts;

District entity:

/**
 *
 * @var \Doctrine\Common\Collections\ArrayCollection $articles
 * @ORM\ManyToMany(targetEntity="Article", inversedBy="districts")
 */
protected $articles;

Question

The two extra tables that are being created are: articles_districts (the one I specified in the JoinTable section) and article_district (the other one that somehow gets created automatically).

The articles_districts table works as expected and ID's are inserted when a new entry is made. The article_district remains empty, and thus, is pretty useless. How do I get rid of it?

like image 852
thomastuts Avatar asked Jan 15 '13 11:01

thomastuts


1 Answers

Your district entity should use the mappedBy annotation:

/**
 *
 * @var \Doctrine\Common\Collections\ArrayCollection $articles
 * @ORM\ManyToMany(targetEntity="Article", mappedBy="districts")
 */
protected $articles;

At the moment you are trying to have two owning sides to your entity relationship: http://docs.doctrine-project.org/en/2.0.x/reference/association-mapping.html#many-to-many-bidirectional

like image 82
Luke Avatar answered Oct 26 '22 23:10

Luke