【发布时间】:2018-02-19 23:21:24
【问题描述】:
我决定为类别实体实现递归的一对一关系:
<?php
/**
* @ORM\Entity(repositoryClass="App\Repository\CategoryRepository")
*/
class Category{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
protected $id;
/**
* @ORM\Column(type="string", length=60, unique=true, nullable=false)
*/
private $name;
/**
* @ORM\OneToOne(targetEntity="App\Entity\Category")
* @ORM\JoinColumn(name="father_id", referencedColumnName="id", nullable=true, onDelete="SET NULL")
*/
private $father;
.................
some methods
.................
}
没有父类别的类别将其属性“父”为空。另一个类别的子类别将具有其父类别的 id。当有两个类别具有相同的父亲时,就会出现问题。错误如下:
An exception occurred while executing 'INSERT INTO category (name, father_id) VALUES (?, ?)' with params ["new category", 1]:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'UNIQ_4E10122D613CEC58'
问题在于,由于某种原因,“father”属性默认为“unique = true”。我试图改变这个属性,设置“unique = false”,但它不起作用。
我听取了这个问题的可能解决方案。非常感谢!
【问题讨论】:
-
您使用的是
OneToOne而不是ManyToOne,因此Doctrine 在您的father_id外键上添加了唯一约束。 This post 更详细地讨论了这种行为。
标签: symfony doctrine one-to-one