php - Doctrine可为空的一对一关系仍然要创建唯一索引

标签 php mysql sql symfony doctrine-orm

我有一个 Person 实体,它与 Location 表有两个关系(hometowncurrent)。这两个字段都可以为 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)。 JoinTableManyToMany 分解为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/

相关文章:

PHP:用其他注释替换 CSS 注释

mysql - 将数据增长到另一个表 - 数据库设计

sql - 需要使用 ms sql 将时间转换为数字

sql - 从查询返回的日期时间值中删除时间

PHP - 将数据从一个站点安全地传递到另一个站点

php - 显示 PHP 源代码的网站

mysql - 由于 'Sending passwords in plain text without SSL/TLS is extremely insecure.',ansible mysql 复制无法将 master 更改为

sql - 从 PostgreSQL 中的行生成系列

具有 2 个计数和连接的 php 查询

mysql - 计算除夏季以外的产品生命周期中的天数