【问题标题】:Attribute unique in one to one relationship - Symfony一对一关系中唯一的属性 - Symfony
【发布时间】: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”,但它不起作用。

我听取了这个问题的可能解决方案。非常感谢!

【问题讨论】:

标签: symfony doctrine one-to-one


【解决方案1】:

如果您使用一对一的关系,“父亲”类别只能有一个“女儿”类别。你想要的是一个类别“父亲”可以有几个类别“女儿”。你需要一个one-to-many relationship self-referencing.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    相关资源
    最近更新 更多