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

时间:2015-12-17 06:57:22

标签: php symfony doctrine-orm 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. 

1 个答案:

答案 0 :(得分:2)

字段定义错误。您应该只定义关系的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。 ManyToMany协会的拥有和反面

     

对于多对多关联,您可以选择哪个实体是拥有者,哪个实体是反面。从开发人员的角度来看,有一个非常简单的语义规则来决定哪一方更适合作为拥有方。您只需要问问自己,哪个实体负责连接管理,并选择作为拥有方。