我有两个具有多对多关系的模型。该ID不受教义管理,而是由其他应用程序的GUID生成器管理。因此,我的实体有一个名为uniqueIdentifier
而不是id
的字段。这样做:
class Bar {
/**
* @ManyToMany(targetEntity="Foo", mappedBy="bar")
*/
private $foo;
}
class Foo {
/**
* @ManyToMany(targetEntity="Bar", mappedBy="foo")
*/
private $bar;
}
我收到一个错误,指出是Column name 'id' referenced for relation from App\Entity\Foo towards App\Entity\Bar does not exist
。我知道这是由于在理论上默认,将内容映射到_id
作为参考列名,将table1_table2
映射到联接表。
我无法覆盖默认值,因为一些模型确实具有自动生成的值并且依赖于id
字段。相反,我想执行以下操作:
class Bar {
/**
* @ManyToMany(targetEntity="Foo", mappedBy="bar")
* @JoinColumn(name="foo_uid", referencedColumnName="uniqueIdentifier")
*/
private $foo;
}
class Foo {
/**
* @ManyToMany(targetEntity="Bar", mappedBy="foo")
* @JoinColumn(name="bar_uid", referencedColumnName="uniqueIdentifier")
*/
private $bar;
}
这不起作用,并且出现相同的错误。怎么办?
您的关联映射应该是这样的:
class Bar
{
/**
* @var Foo[]|\Doctrine\Common\Collections\Collection
*
* @ORM\ManyToMany(targetEntity="Foo", inversedBy="bar")
* @ORM\JoinTable(
* name="table1_table2",
* joinColumns={@ORM\JoinColumn(name="foo_uid", referencedColumnName="uniqueIdentifier")},
* inverseJoinColumns={@ORM\JoinColumn(name="bar_uid", referencedColumnName="uniqueIdentifier")}
* )
*/
private $foo;
}
class Foo {
/**
* @var Bar[]|\Doctrine\Common\Collections\Collection
*
* @ORM\ManyToMany(targetEntity="Bar", mappedBy="foo")
*/
private $bar;
}
记住foo_uid
和bar_uid
列将在table1_table2
表中,并且uniqueIdentifier
是Foo和Bar的表上的标识符。