Doctrine2 中的多对多关系导致迁移中的重复错误

Many-to-many relation in Doctrine2 leads to duplication error in migration

我在我的项目中创建了两个基于 Symfony2 框架的 Doctrine2 实体。该实体具有多对多关系。 有我的模特:

/**
 * @ORM\Entity
 * @ORM\Table(name="first")
 */
class First
{
    ...

    /**
     * @var Second[]|Collection
     *
     * @ORM\ManyToMany(targetEntity="MyBundle\Entity\Second", cascade={"detach"})
     * @ORM\JoinTable(name="first_to_second",
     *      joinColumns={@ORM\JoinColumn(name="first_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="second_id", referencedColumnName="id")},
     * )
     */
    private $seconds;

    ...
}

/**
 * @ORM\Entity
 * @ORM\Table(name="second")
 */
class Second
{
    ...

    /**
     * @var First[]|Collection
     *
     * @ORM\ManyToMany(targetEntity="MyBundle\Entity\First", cascade={"remove"})
     * @ORM\JoinTable(name="first_to_second",
     *      joinColumns={@ORM\JoinColumn(name="second_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="first_id", referencedColumnName="id")},
     * )
     */
    private $firsts;

    ...
}

当我尝试进行迁移时

$ php app/console doctrine:migration:diff

出现错误:

[Doctrine\DBAL\Schema\SchemaException]
The table with name 'first_to_second' already exists.

字段定义错误。您应该只定义关系的 JoinTable 一侧(拥有方),并通过 mappedByinversedBy.

定义哪一侧是哪一侧

http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#many-to-many-bidirectional

/** @Entity */
class User
{
    // ...

    /**
     * @ManyToMany(targetEntity="Group", inversedBy="users")
     * @JoinTable(name="users_groups")
     */
    private $groups;

    public function __construct() {
        $this->groups = new \Doctrine\Common\Collections\ArrayCollection();
    }

    // ...
}

/** @Entity */
class Group
{
    // ...
    /**
     * @ManyToMany(targetEntity="User", mappedBy="groups")
     */
    private $users;

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

    // ...
}

5.9.1. Owning and Inverse Side on a ManyToMany association

For Many-To-Many associations you can chose which entity is the owning and which the inverse side. There is a very simple semantic rule to decide which side is more suitable to be the owning side from a developers perspective. You only have to ask yourself, which entity is responsible for the connection management and pick that as the owning side.