我有一个 Person
实体,它与 Location
表有两个关系(hometown
和 current
)。这两个字段都可以为 null,否则它们必须存在于 Location
表中:
class Person {
.....
/**
* @var Location
* @ORM\OneToOne(targetEntity="Location")
* @ORM\JoinColumn(name="hometown_id", referencedColumnName="id",nullable=true)
**/
protected $hometown;
/**
* @var Location
* @ORM\OneToOne(targetEntity="Location")
* @ORM\JoinColumn(name="current_id", referencedColumnName="id", nullable=true)
**/
protected $current;
....
}
现在,我想根据 doctrine:schema:update --dump-sql
输出更新我的数据库架构,但它会产生问题:
CREATE UNIQUE INDEX UNIQ_8D93D6494341EE7D ON person (hometown_id);
CREATE UNIQUE INDEX UNIQ_8D93D649B8998A57 ON person (current_id);
我无法定义这些索引,因为表中存在多个空行。
你能帮我一下吗?
最佳答案
OneToOne
关系是唯一的,因为它意味着只能将一个人
分配给一个位置
和一个位置
给一个人
。
在您的场景中,您希望一个人
拥有多个位置,一个位置
可以拥有多个人
。这将是一个ManyToMany
关系。
在 Doctrine 中,当您使用 ManyToMany
时,您将指定 Doctrine 将管理的 JoinTable
(您不必为 JoinTable
)。 JoinTable
将ManyToMany
分解为OneToMany
之类的东西,例如一个人
到多个位置
(s) 如下例所示。 JoinTable
将在应用时存储您想要的值。
/**
* @ORM\ManyToMany(targetEntity="Location")
* @ORM\JoinTable(name="hometown_location",
* joinColumns={@ORM\JoinColumn(name="person_id", referencedColumnName="id", unique=true)},
* inverseJoinColumns={@ORM\JoinColumn(name="location_id", referencedColumnName="id")}
* )
**/
protected $hometown;
/**
* @ORM\ManyToMany(targetEntity="Location")
* @ORM\JoinTable(name="current_location",
* joinColumns={@ORM\JoinColumn(name="person_id", referencedColumnName="id", unique=true)},
* inverseJoinColumns={@ORM\JoinColumn(name="location_id", referencedColumnName="id")}
* )
**/
protected $current;
public function __construct() {
$this->hometown = new \Doctrine\Common\Collections\ArrayCollection();
$this->hometown = new \Doctrine\Common\Collections\ArrayCollection();
}
如果没有可以分配给家乡
或当前
的位置
,也可以,不会占用任何空间。
当您确实有一个位置
可以分配给家乡
或当前
时,它必须是有效的位置
位置
表。
关于php - Doctrine可为空的一对一关系仍然要创建唯一索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18971781/