Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

php - Is it possible to reference a column other than 'id' for a JoinColumn?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think Doctrine wants these to be primary keys, from the docs:

name: Column name that holds the foreign key identifier for this relation.

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.

You may be able to get away with just @Index on category.id2 and leave it as a string though; worth a shot anyway.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...