ManyToMany的2个实例用于同一个类中的同一个实体

时间:2012-07-31 12:18:54

标签: php doctrine-orm

我想添加具有manyToMany关系的同一对象的2个实例。

class A {

     /**

 * @ORM\ManyToMany(targetEntity="RelatedEntity", inversedBy="teachers", cascade={"persist", "remove"})
 * @ORM\JoinTable(name="table1",
 *      joinColumns={@ORM\JoinColumn(name="class_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="related_id", referencedColumnName="id")}
 *      )
 */
protected $myFirstEntities;


     /**

 * @ORM\ManyToMany(targetEntity="RelatedEntity", inversedBy="students", cascade={"persist", "remove"})
 * @ORM\JoinTable(name="table2",
 *      joinColumns={@ORM\JoinColumn(name="class_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="related_id", referencedColumnName="id")}
 *      )
 */
protected $mySecondEntities;
}



class RelatedEntity
{
  /**
 *
 * @ORM\ManyToMany(targetEntity="A", mappedBy="myFirstEntities", cascade={"persist"})
 */
protected $teachers;

  /**
 *
 * @ORM\ManyToMany(targetEntity="A", mappedBy="mySecondEntities", cascade={"persist"})
 */
protected $students;

}

当我使用

        php app/console doctrine:generate:entities MyApp

程序生成添加实体的唯一方法:

public function addRelatedEntity(\MyApp\MyBundle\Entity\RelatedEntity $myFirstEntities)
{
    $this->myFirstEntities[] = $myFirstEntities;
}

所以我不能添加mySecondEntities。我该怎么做。我有可能在手动方法中添加它但是自动方法不可能吗?

我的问题是,我可以将特定类的2多个关系用于同一个类吗?我该怎么办?

1 个答案:

答案 0 :(得分:0)

doctrine:generate:当你需要生成实体时应该使用的实体,它不能保证生成的映射100%正确,http://docs.doctrine-project.org/projects/doctrine-orm/en/2.0.x/reference/tools.html#entity-generation

  

此命令不适合持续使用。这是一个小帮手   并且不能很好地支持所有映射边缘情况。你还在   使用此命令后,必须将工作放在实体中。

您可以为同一个班级进行多对多映射,只需手动执行

即可
public function addFirstEntity(\MyApp\MyBundle\Entity\RelatedEntity $myFirstEntities)
{
    $this->myFirstEntities[] = $myFirstEntities;
} 

public function addSecondEntity(\MyApp\MyBundle\Entity\RelatedEntity $mySecondEntities)
{
    $this->mySecondEntities[] = $mySecondEntities;
}