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;
When I try saving an Item
I get this error:
Notice: Undefined index: id2 in vendor/doctrine/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php line 511
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?
Edit
What I want to achieve is impossible according to the official Doctrine 2 docs.
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.
source: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/limitations-and-known-issues.html#join-columns-with-non-primary-keys
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…