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

Closed
doctrinebot opened this Issue Nov 5, 2009 · 25 comments

2 participants

@doctrinebot

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

@doctrinebot

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

Comment created by romanb:

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

@doctrinebot

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

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

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)
@doctrinebot

Comment created by mstoehr:

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

@doctrinebot

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

Comment created by s9e:

SAPK with user-defined column names

@doctrinebot

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

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

@doctrinebot

Comment created by @beberlei:

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

@doctrinebot

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

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

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

Comment created by @beberlei:

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

@doctrinebot

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 140ddf5 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

Comment created by @beberlei:

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

@doctrinebot

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

Comment created by @beberlei:

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

@doctrinebot

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

Issue was closed with resolution "Fixed"

@doctrinebot

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

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.

@beberlei beberlei was assigned by doctrinebot Dec 6, 2015
@doctrinebot doctrinebot added this to the 2.1 milestone Dec 6, 2015
@doctrinebot doctrinebot closed this Dec 6, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment