【问题标题】:Is it possible to reference a column other than 'id' for a JoinColumn?是否可以为 JoinColumn 引用除“id”之外的列?
【发布时间】:2019-09-09 00:45:21
【问题描述】:

我有一个Item 实体,它与Category 实体有ManyToOne 关系。我希望它们通过类别的id 以外的字段加入(在本例中,是一个名为id2 的字段)。我的架构如下所示。

class Item {
    /**
     * @ORM\Id
     * @ORM\Column(name = "id", type = "integer")
     * @ORM\GeneratedValue(strategy = "AUTO")
     */
    protected $id;
    /**
     * @ORM\ManyToOne(targetEntity = "Category")
     * @ORM\JoinColumn(name = "category_id", referencedColumnName = "id2")
     */
    protected $category;
}

class Category {
    /**
     * @ORM\Id
     * @ORM\Column(name = "id", type = "integer")
     * @ORM\GeneratedValue(strategy = "AUTO")
     */
    protected $id;
    /**
     * @ORM\Column(name = "id2", type = "string", length = "255", unique = "true")
     */
    protected $id2;

当我尝试保存 Item 时,我收到此错误:

注意:未定义索引:在 vendor/doctrine/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php 行 511 中的 id2

果然,如果我在JoinColumn 注释中将id2 更改为id,一切正常,但我需要通过id2 连接实体。这可能吗?

编辑
根据官方 Doctrine 2 文档,我想要实现的目标是不可能的。

不能使用指向非主键的连接列。 Doctrine 会认为这些是主键并创建延迟加载 代理与数据,这可能会导致意想不到的结果。教义 可以出于性能原因不验证这个的正确性 在运行时设置,但只能通过 Validate Schema 命令。

来源:https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/limitations-and-known-issues.html#join-columns-with-non-primary-keys

【问题讨论】:

    标签: php doctrine-orm


    【解决方案1】:

    我认为 Doctrine 希望这些是主键,来自 the docs:

    name:包含此关系的外键标识符的列名。

    从您的代码示例中跳出来的另一件事是 category.id2 是 type string,我至少希望它是一个整数,但它可能还需要 @JoinColumn 才能正常工作。

    您也许可以在 category.id2 上只使用 @Index 并将其保留为 string;无论如何都值得一试。

    【讨论】:

    • 感谢您的回复。我尝试将字段类型更改为整数,并添加@Index,但它仍然不起作用。
    • 呸!看起来他们毕竟需要是fks。总是有多对多作为一种选择。
    【解决方案2】:

    只是为了报告。我能够以 Many2One(单向)关系加入非 PK,但我的对象无法以正常方式加载。它必须使用 DQL 加载,例如:

    SELECT d,u FROM DEntity d
        JOIN d.userAccount u
    

    这样我就不再报错了:...上的主键 ID 缺少值。

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-02
      • 2020-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多