DDC-117: Allow @Id on @ManyToOne fields #148

Closed
opened 2026-01-22 12:28:35 +01:00 by admin · 25 comments
Owner

Originally created by @doctrinebot on GitHub (Nov 5, 2009).

Originally assigned to: @beberlei on GitHub.

Jira issue originally created by user nicokaiser:

Sometimes, a @ManyToOne field has to be the Primary Key, or part of the Primary Key. Adding @Id to the @ManyToOne does not help, an additional property with duplicates the referenced id is needed:

(userId and User field in the Phonenumber class - to be able to set @Id on userId):
http://pastebin.com/d51e021e2

Allowing @Id on @ManyToOne fields (which would make the JoinColumn a PK) would help here. Any maybe this would also fix DDC-116

Originally created by @doctrinebot on GitHub (Nov 5, 2009). Originally assigned to: @beberlei on GitHub. Jira issue originally created by user nicokaiser: Sometimes, a @ManyToOne field has to be the Primary Key, or part of the Primary Key. Adding @Id to the @ManyToOne does not help, an additional property with duplicates the referenced id is needed: (userId and User field in the Phonenumber class - to be able to set @Id on userId): http://pastebin.com/d51e021e2 Allowing @Id on @ManyToOne fields (which would make the JoinColumn a PK) would help here. Any maybe this would also fix [DDC-116](http://www.doctrine-project.org/jira/browse/DDC-116)
admin added the New Feature label 2026-01-22 12:28:35 +01:00
admin closed this issue 2026-01-22 12:28:36 +01:00
Author
Owner

@doctrinebot commented on GitHub (Nov 5, 2009):

@doctrinebot commented on GitHub (Nov 5, 2009): - is duplicated by [DDC-795: Wrong SQL statement when using loadOneToManyCollection](http://www.doctrine-project.org/jira/browse/DDC-795)
Author
Owner

@doctrinebot commented on GitHub (Dec 7, 2009):

Comment created by nicokaiser:

Thanks for your reply on doctrine-user!

My previous workaround was something like this:
http://pastie.org/private/uoawwvf75onnvph8bj1fwg

Instead of just having a $User property in the Phonenumber entity (which is mapped by the userId field in the phonenumber table), I have an additional $userId property, which is also mapped to the userId DB field. This way I could make $userId @Id (and thus add it to the PKs), but I had to manually update it when I set the $User (see the TODO annotations in the Pastie code).

I see "EntityManager#find(...)" would have to be able to also get objects as identifiers, e.g. (int, User), which may have major implications...

However I think to support constructions like this is very important as it's a very common pattern, especially for OneToOne associations with no additional identifier field (PK = FK)...

@doctrinebot commented on GitHub (Dec 7, 2009): Comment created by nicokaiser: Thanks for your reply on doctrine-user! My previous workaround was something like this: http://pastie.org/private/uoawwvf75onnvph8bj1fwg Instead of just having a $User property in the Phonenumber entity (which is mapped by the userId field in the phonenumber table), I have an additional $userId property, which is also mapped to the userId DB field. This way I could make $userId @Id (and thus add it to the PKs), but I had to manually update it when I set the $User (see the TODO annotations in the Pastie code). I see "EntityManager#find(...)" would have to be able to also get objects as identifiers, e.g. (int, User), which may have major implications... However I think to support constructions like this is very important as it's a very common pattern, especially for OneToOne associations with no additional identifier field (PK = FK)...
Author
Owner

@doctrinebot commented on GitHub (Dec 17, 2009):

Comment created by romanb:

We might need to introduce the concept of an IdClass for this in order to be implemented decently.

@doctrinebot commented on GitHub (Dec 17, 2009): Comment created by romanb: We might need to introduce the concept of an IdClass for this in order to be implemented decently.
Author
Owner

@doctrinebot commented on GitHub (Jun 15, 2010):

Comment created by mstoehr:

I just ran into this exact issue. Is there any decent way to work around this issue as the pastie.org-Link is already gone?

@doctrinebot commented on GitHub (Jun 15, 2010): Comment created by mstoehr: I just ran into this exact issue. Is there any decent way to work around this issue as the pastie.org-Link is already gone?
Author
Owner

@doctrinebot commented on GitHub (Jun 15, 2010):

Comment created by nicokaiser:

In an Entity (e.g. "Phonenumber") with PrimaryKey userId you can do something like this:

/****
 * @ManyToOne(targetEntity="Entities\User", inversedBy="Phonenumbers")
 * @JoinColumn(name="userId", referencedColumnName="id")
 */
protected $User;

/****
 * @Id
 * @Column(name="userId", type="integer")
 */
protected $userId;

public function setUser(\Entities\User $user)
{
    $this->User = $user;
    $this->userId = $user->getId();
}
@doctrinebot commented on GitHub (Jun 15, 2010): Comment created by nicokaiser: In an Entity (e.g. "Phonenumber") with PrimaryKey userId you can do something like this: ``` /**** * @ManyToOne(targetEntity="Entities\User", inversedBy="Phonenumbers") * @JoinColumn(name="userId", referencedColumnName="id") */ protected $User; /**** * @Id * @Column(name="userId", type="integer") */ protected $userId; public function setUser(\Entities\User $user) { $this->User = $user; $this->userId = $user->getId(); } ```
Author
Owner

@doctrinebot commented on GitHub (Aug 7, 2010):

Comment created by @beberlei:

I took the time today and tried what is possible to hack in this regard and came up with a pretty trivial solution for this. This is a very early draft of this functionality as it might be included in 2.1

http://github.com/doctrine/doctrine2/commits/DDC-117

What works?

  • Association Only Composite Primary Keys (Reference with SourceArticle to TargetArticle)
  • Mixed Composite Primary Keys (ArticleTranslation with Article + Language)
  • Single Association Primary Keys (Article and ArticleDetails)
@doctrinebot commented on GitHub (Aug 7, 2010): Comment created by @beberlei: I took the time today and tried what is possible to hack in this regard and came up with a pretty trivial solution for this. This is a very early draft of this functionality as it might be included in 2.1 http://github.com/doctrine/doctrine2/commits/[DDC-117](http://www.doctrine-project.org/jira/browse/DDC-117) What works? - Association Only Composite Primary Keys (Reference with SourceArticle to TargetArticle) - Mixed Composite Primary Keys (ArticleTranslation with Article + Language) - Single Association Primary Keys (Article and ArticleDetails)
Author
Owner

@doctrinebot commented on GitHub (Aug 7, 2010):

Comment created by mstoehr:

Wow, great work, Benjamin. Will try it out ASAP and when it works, I'll owe you a beer. ;)

@doctrinebot commented on GitHub (Aug 7, 2010): Comment created by mstoehr: Wow, great work, Benjamin. Will try it out ASAP and when it works, I'll owe you a beer. ;)
Author
Owner

@doctrinebot commented on GitHub (Aug 8, 2010):

Comment created by s9e:

I'm having troubles with user-defined column names used in SAPK. The schema tool complains that the column name doesn't exist. I've reduced it to a small testcase based on DDC117Test.

@doctrinebot commented on GitHub (Aug 8, 2010): Comment created by s9e: I'm having troubles with user-defined column names used in SAPK. The schema tool complains that the column name doesn't exist. I've reduced it to a small testcase based on DDC117Test.
Author
Owner

@doctrinebot commented on GitHub (Aug 8, 2010):

Comment created by s9e:

SAPK with user-defined column names

@doctrinebot commented on GitHub (Aug 8, 2010): Comment created by s9e: SAPK with user-defined column names
Author
Owner

@doctrinebot commented on GitHub (Aug 15, 2010):

Comment created by @beberlei:

I fixed another bunch of issues with hydration and updating of assoc-id entities.

@s9e i will now tackle your issue.

@doctrinebot commented on GitHub (Aug 15, 2010): Comment created by @beberlei: I fixed another bunch of issues with hydration and updating of assoc-id entities. @s9e i will now tackle your issue.
Author
Owner

@doctrinebot commented on GitHub (Aug 15, 2010):

Comment created by @beberlei:

@s9e you forgot to define the @JoinColumn annotation correctly. that is necessary when you rename the ID column on the other side. See my current commit, it works for me!

The commit is: 772e592489

@doctrinebot commented on GitHub (Aug 15, 2010): Comment created by @beberlei: @s9e you forgot to define the @JoinColumn annotation correctly. that is necessary when you rename the ID column on the other side. See my current commit, it works for me! The commit is: http://github.com/doctrine/doctrine2/commit/772e5924898326de2c769c4cb0c6874fde4edc45
Author
Owner

@doctrinebot commented on GitHub (Aug 15, 2010):

Comment created by @beberlei:

Add current version of the patch diffed against the master from today, for easier testing and review.

@doctrinebot commented on GitHub (Aug 15, 2010): Comment created by @beberlei: Add current version of the patch diffed against the master from today, for easier testing and review.
Author
Owner

@doctrinebot commented on GitHub (Aug 15, 2010):

Comment created by s9e:

@Benjamin Eberlei - Actually it's the other way around. I have defined @JoinColumn on both sides of the relationship, and SchemaTool doesn't like that. After removing @JoinColumn from the inverse side, SchemaTool processes the entities as expected, so I'm not sure whether it should be considered a bug or a feature. If @JoinColumn should only be defined on the owning side, please add a note to the manual.

Anyway, the schema now works but I'm still having troubles persisting through cascade. Test attached.

@doctrinebot commented on GitHub (Aug 15, 2010): Comment created by s9e: @Benjamin Eberlei - Actually it's the other way around. I have defined @JoinColumn on both sides of the relationship, and SchemaTool doesn't like that. After removing @JoinColumn from the inverse side, SchemaTool processes the entities as expected, so I'm not sure whether it should be considered a bug or a feature. If @JoinColumn should only be defined on the owning side, please add a note to the manual. Anyway, the schema now works but I'm still having troubles persisting through cascade. Test attached.
Author
Owner

@doctrinebot commented on GitHub (Aug 16, 2010):

Comment created by @beberlei:

the @joinColumn is explained in the association mapping chapter. There are examples for each cases, showing where to put the annotation and where not.

The Persist Cascade i pick up next then.

@doctrinebot commented on GitHub (Aug 16, 2010): Comment created by @beberlei: the @joinColumn is explained in the association mapping chapter. There are examples for each cases, showing where to put the annotation and where not. The Persist Cascade i pick up next then.
Author
Owner

@doctrinebot commented on GitHub (Aug 17, 2010):

Comment created by mjh_ca:

Hi Benjamin, great work on this. Testing it out now. One problem (do you want a ticket opened?). Using the latest DDC-117 branch, schema tool crates both a PRIMARY KEY and a UNIQUE KEY (at least in MySQL) on the same columns. The UNIQUE KEY is really not necessary, right?

/*** @Entity **/
class Foo {
    /****
     * @Id @Column(type="integer")
     * @GeneratedValue
     */
    protected $id;
}

/*** @Entity **/
class Bar {
    /****
     * @Id
     * @OneToOne(targetEntity="Foo")
     * @JoinColumn(name="foo_id", referencedColumnName="id")
     */
    protected $fooId;
}

Produces:

CREATE TABLE Bar (foo*id INT NOT NULL, UNIQUE INDEX Bar_foo_id_uniq (foo_id), PRIMARY KEY(foo*id)) ENGINE = InnoDB;
CREATE TABLE Foo (id INT AUTO_INCREMENT NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB;

Expected:

CREATE TABLE Bar (foo*id INT NOT NULL, PRIMARY KEY(foo*id)) ENGINE = InnoDB;
CREATE TABLE Foo (id INT AUTO_INCREMENT NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB;
@doctrinebot commented on GitHub (Aug 17, 2010): Comment created by mjh_ca: Hi Benjamin, great work on this. Testing it out now. One problem (do you want a ticket opened?). Using the latest [DDC-117](http://www.doctrine-project.org/jira/browse/DDC-117) branch, schema tool crates both a PRIMARY KEY and a UNIQUE KEY (at least in MySQL) on the same columns. The UNIQUE KEY is really not necessary, right? ``` /*** @Entity **/ class Foo { /**** * @Id @Column(type="integer") * @GeneratedValue */ protected $id; } /*** @Entity **/ class Bar { /**** * @Id * @OneToOne(targetEntity="Foo") * @JoinColumn(name="foo_id", referencedColumnName="id") */ protected $fooId; } ``` Produces: ``` CREATE TABLE Bar (foo*id INT NOT NULL, UNIQUE INDEX Bar_foo_id_uniq (foo_id), PRIMARY KEY(foo*id)) ENGINE = InnoDB; CREATE TABLE Foo (id INT AUTO_INCREMENT NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB; ``` Expected: ``` CREATE TABLE Bar (foo*id INT NOT NULL, PRIMARY KEY(foo*id)) ENGINE = InnoDB; CREATE TABLE Foo (id INT AUTO_INCREMENT NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB; ```
Author
Owner

@doctrinebot commented on GitHub (Aug 17, 2010):

Comment created by @beberlei:

No, all the issues on this ticket. I branch them into subtickets if necessary.

@doctrinebot commented on GitHub (Aug 17, 2010): Comment created by @beberlei: No, all the issues on this ticket. I branch them into subtickets if necessary.
Author
Owner

@doctrinebot commented on GitHub (Nov 14, 2010):

Comment created by mjh_ca:

Hi Benjamin - would you mind doing a merge from current master to DDC-117 branch? Been using it for devel and it is working quite well but commit 140ddf5098 on Sept 27 causes a merge conflict. Looks like it is easy to resolve but it would be great if it could be merged into your DDC-117 so extra steps aren't required to clone/checkout DDC-117.

@doctrinebot commented on GitHub (Nov 14, 2010): Comment created by mjh_ca: Hi Benjamin - would you mind doing a merge from current master to [DDC-117](http://www.doctrine-project.org/jira/browse/DDC-117) branch? Been using it for devel and it is working quite well but commit 140ddf5098a7ffdf6bc3 on Sept 27 causes a merge conflict. Looks like it is easy to resolve but it would be great if it could be merged into your [DDC-117](http://www.doctrine-project.org/jira/browse/DDC-117) so extra steps aren't required to clone/checkout [DDC-117](http://www.doctrine-project.org/jira/browse/DDC-117).
Author
Owner

@doctrinebot commented on GitHub (Dec 28, 2010):

Comment created by @beberlei:

I updated the branch to integrate with the current master and attached a new patch to the ticket.

@doctrinebot commented on GitHub (Dec 28, 2010): Comment created by @beberlei: I updated the branch to integrate with the current master and attached a new patch to the ticket.
Author
Owner

@doctrinebot commented on GitHub (Dec 28, 2010):

Comment created by @beberlei:

@S9e: Yes this is obvious, it works only with Sequence as ID Generation strategy (for example with PostgreSQL)

The problem is, during persist MySQL and SQLite don't know the value of the primary key yet. However for the @id @ManyToOne patch to work it is necessary that all the dependencies primary keys are already known. That is why two step flush procedures are sometimes necessary.

  1. persist non fkpk entities and flush them
  2. persist fk+pk entities then flush them
@doctrinebot commented on GitHub (Dec 28, 2010): Comment created by @beberlei: @S9e: Yes this is obvious, it works only with Sequence as ID Generation strategy (for example with PostgreSQL) The problem is, during persist MySQL and SQLite don't know the value of the primary key yet. However for the @id <ins> @ManyToOne patch to work it is necessary that all the dependencies primary keys are already known. That is why two step flush procedures are sometimes necessary. 1. persist non fk</ins>pk entities and flush them 2. persist fk+pk entities then flush them
Author
Owner

@doctrinebot commented on GitHub (Jan 1, 2011):

Comment created by @beberlei:

Patch is now finished and will be merged into master tomorrow.

@doctrinebot commented on GitHub (Jan 1, 2011): Comment created by @beberlei: Patch is now finished and will be merged into master tomorrow.
Author
Owner

@doctrinebot commented on GitHub (Jan 2, 2011):

Comment created by @beberlei:

Merged into master and scheduled for 2.1.

Please test this patch extensively, there are tons of examples in tests/Doctrine/Tests/Models/DDC117 and tests/Doctrine/Tests/ORM/Functional/Ticket/DDC117Test.php

@doctrinebot commented on GitHub (Jan 2, 2011): Comment created by @beberlei: Merged into master and scheduled for 2.1. Please test this patch extensively, there are tons of examples in tests/Doctrine/Tests/Models/DDC117 and tests/Doctrine/Tests/ORM/Functional/Ticket/DDC117Test.php
Author
Owner

@doctrinebot commented on GitHub (Jan 2, 2011):

Issue was closed with resolution "Fixed"

@doctrinebot commented on GitHub (Jan 2, 2011): Issue was closed with resolution "Fixed"
Author
Owner

@doctrinebot commented on GitHub (Jan 9, 2011):

Comment created by henrikbjorn:

@Benjamin

I have created a OneToOne relation on a User -> Profile where the profile is specified as the inverse side so i can have user_id be the primary key. And it all works as expected except that when i create a new User (The Profile object is getting created in the user constructor) and persist it (the relation have cascade-all specified) i end up with the error "The given entity has no identity.". But if i persist the user without creating the profile inside it and fliush and then create a Profile object and persist and flush that it all work.

It seems like it dosent know that the User should be saved first so that it have an id and then save the profile. Dont know if this is a bug or it is expected behavior.

@doctrinebot commented on GitHub (Jan 9, 2011): Comment created by henrikbjorn: @Benjamin I have created a OneToOne relation on a User -> Profile where the profile is specified as the inverse side so i can have user_id be the primary key. And it all works as expected except that when i create a new User (The Profile object is getting created in the user constructor) and persist it (the relation have cascade-all specified) i end up with the error "The given entity has no identity.". But if i persist the user without creating the profile inside it and fliush and then create a Profile object and persist and flush that it all work. It seems like it dosent know that the User should be saved first so that it have an id and then save the profile. Dont know if this is a bug or it is expected behavior.
Author
Owner

@doctrinebot commented on GitHub (Jan 9, 2011):

Comment created by @beberlei:

expected behavior, you are using the id generator "assigned" which means on persist the id has to be assigned. In your case it isnt, because the related object has not been assigned an id itself, thus failing.

@doctrinebot commented on GitHub (Jan 9, 2011): Comment created by @beberlei: expected behavior, you are using the id generator "assigned" which means on persist the id has to be assigned. In your case it isnt, because the related object has not been assigned an id itself, thus failing.
Author
Owner

@doctrinebot commented on GitHub (Dec 13, 2015):

Imported 3 attachments from Jira into https://gist.github.com/b683ca5f10bf1aad232c

@doctrinebot commented on GitHub (Dec 13, 2015): Imported 3 attachments from Jira into https://gist.github.com/b683ca5f10bf1aad232c - [10741_ddc117_20100815.patch](https://gist.github.com/b683ca5f10bf1aad232c#file-10741_ddc117_20100815-patch) - [10742_ddc117test_cascade_persist.patch](https://gist.github.com/b683ca5f10bf1aad232c#file-10742_ddc117test_cascade_persist-patch) - [10902_ddc117-20101228.diff](https://gist.github.com/b683ca5f10bf1aad232c#file-10902_ddc117-20101228-diff)
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: doctrine/archived-orm#148