是否可以为 JoinColumn 引用除“id"之外的列?
我有一个 Item
实体,它与 Category
实体具有 ManyToOne
关系.我希望它们通过类别的 id
以外的字段(在本例中为名为 id2
的字段)加入.我的架构如下所列.
I have an Item
entity that has a ManyToOne
relationship to a Category
entity. I want them to be joined by a field other than Category's id
(in this case, a field called id2
). My schema is listed below.
class Item {
/**
* @ORMId
* @ORMColumn(name = "id", type = "integer")
* @ORMGeneratedValue(strategy = "AUTO")
*/
protected $id;
/**
* @ORMManyToOne(targetEntity = "Category")
* @ORMJoinColumn(name = "category_id", referencedColumnName = "id2")
*/
protected $category;
}
class Category {
/**
* @ORMId
* @ORMColumn(name = "id", type = "integer")
* @ORMGeneratedValue(strategy = "AUTO")
*/
protected $id;
/**
* @ORMColumn(name = "id2", type = "string", length = "255", unique = "true")
*/
protected $id2;
当我尝试保存 Item
时,出现此错误:
When I try saving an Item
I get this error:
注意:未定义索引:id2 in vendor/doctrine/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php line 511
Notice: Undefined index: id2 in vendor/doctrine/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php line 511
果然,如果我在 JoinColumn
注释中将 id2
更改为 id
,一切正常,但我需要连接实体通过 id2
.这可能吗?
Sure enough, if I change id2
to id
in the JoinColumn
annotation, everything works fine, but I need the entities to be connected through id2
. Is this possible?
编辑
根据官方Doctrine 2文档,我想要实现的目标是不可能的.
Edit
What I want to achieve is impossible according to the official Doctrine 2 docs.
不能使用指向非主键的连接列.Doctrine 会认为这些是主键并创建延迟加载代理数据,这可能会导致意想不到的结果.教义可以出于性能原因无法验证此的正确性在运行时进行设置,但只能通过 Validate Schema 命令进行设置.
It is not possible to use join columns pointing to non-primary keys. Doctrine will think these are the primary keys and create lazy-loading proxies with the data, which can lead to unexpected results. Doctrine can for performance reasons not validate the correctness of this settings at runtime but only through the Validate Schema command.
来源:https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/limitations-and-known-issues.html#join-columns-with-non-primary-keys
推荐答案
我认为 Doctrine 希望这些成为主键,来自 文档:
I think Doctrine wants these to be primary keys, from the docs:
name:保存此关系的外键标识符的列名.
name: Column name that holds the foreign key identifier for this relation.
从你的代码示例中跳出来的另一件事是 category.id2 是 type string,我至少希望它是一个整数,但它也可能需要 @JoinColumn 才能正常工作.
Another thing that jumps out at me from your code sample is category.id2 being type string, I would at least expect it to be an integer, but it may also need to be for @JoinColumn to work properly.
您可能只需要 category.id2 上的 @Index 并将其保留为 string;无论如何值得一试.
You may be able to get away with just @Index on category.id2 and leave it as a string though; worth a shot anyway.
相关文章