为什么doctrine迁移尝试在ManyToMany关系上创建2个表

时间:2015-11-14 02:26:30

标签: symfony doctrine many-to-many

我在两个实体之间声明了ManyToMany关系,当我使用doctrine:migrations:diff时,它会尝试两次创建表并抛出异常“名为'incompass.surgerysurgeryside'的表已经存在”

这是我使用过的注释:

Surgery.php

/**
 * @ORM\ManyToMany(targetEntity="Incompass\SurgeryBundle\Entity\SurgerySide", inversedBy="surgeries")
 * @ORM\JoinTable(name="SurgerySurgerySide",
 *      joinColumns={@ORM\JoinColumn(name="surgery_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="surgery_side_id", referencedColumnName="id")}
 * )
 */
protected $surgery_sides;

SurgerySide.php

/**
 * @ORM\ManyToMany(targetEntity="Incompass\SurgeryBundle\Entity\Surgery", inversedBy="surgery_sides")
 * @ORM\JoinTable(name="SurgerySurgerySide",
 *      joinColumns={@ORM\JoinColumn(name="surgery_side_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="surgery_id", referencedColumnName="id")}
 * )
 */
protected $surgeries;

(NB这里的答案不回答实际问题Doctrine many-to-many relationship wants to create a table twice when I create a migration

1 个答案:

答案 0 :(得分:1)

尝试删除inversedBy或使用一次inversedBymappedBy

/**
 * @ORM\ManyToMany(targetEntity="Incompass\SurgeryBundle\Entity\SurgerySide", inversedBy="surgeries")
 */
 protected $surgery_sides;


/**
 * @ORM\ManyToMany(targetEntity="Incompass\SurgeryBundle\Entity\Surgery", mappedBy="surgery_sides")
 */
protected $surgeries;

解释

Doctrine猜测如何命名表,通常优先级为<firstEntity>_<secondEntity>。由于两者都是inversedBy,因此Doctrine不知道哪个使用第二个,因此创建了两个表。