2

我有一个与表有两个关系(和)的Person实体。这两个字段都可以为空,否则它们必须存在于表中:hometowncurrentLocationLocation

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);

我无法定义这些索引,因为表中有多个空行。

你能帮帮我吗?

4

2 回答 2

3

关系是唯一的OneToOne,因为这意味着只能将一个person分配给 onelocationlocation一对一person

在您的场景中,您可能希望一个person有多个位置,一个location可以有多个person。这将是一种ManyToMany关系。

在 Doctrine 中,当您使用 a 时,ManyToMany您将指定JoinTableDoctrine 将管理的 a(您不必为 a 创建实体JoinTable)。如下面的示例所示,将其JoinTable分解为诸如一对多之ManyToMany类的东西。将在应用时存储您想要的值。OneToManypersonlocationJoinTable

/**
 * @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();
}

如果没有location可分配hometowncurrent没问题,则不占用空间。当您确实有location要分配给其中一个时,hometown或者current它必须是表中的location有效值location

于 2013-09-24T03:23:56.350 回答
0

看起来您正在寻找 FOREIGN KEY

http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html

ALTER TABLE `Person` ADD INDEX ( `hometown_id` ) ;
ALTER TABLE `Person` ADD FOREIGN KEY ( `hometown_id` ) REFERENCES `Location` ( `id` )
ON DELETE RESTRICT ON UPDATE RESTRICT ;

ALTER TABLE `Person` ADD INDEX ( `current_id` ) ;
ALTER TABLE `Person` ADD FOREIGN KEY ( `current_id` ) REFERENCES `Location` ( `id` )
ON DELETE RESTRICT ON UPDATE RESTRICT ;
于 2013-09-24T03:19:30.063 回答