Ми}{@лbI4

Helloworlder's blog

Foreign key as primary key in Doctrine 2

2020-03-09 doctrine, orm, php

Sometimes you need to use a primary key as a foreign key. Someone said, Doctrine ORM doesn't support it, so you have to have unique primary key in each table. Actually this is not necessary, because Doctrin ORM has been supporting it, of the box, since version 2.1. All what we need is association-key attribute (if you use XML entity map; or associationKey for YAML).

Unfortunately, this feature is not obviously. Many people are experiencing difficulties regarding this according to search results. Therefore, I decided to publish a short note about it to make the world a little better.

So, in order to make the primary key as the foreign key we need to specify the same name between them:

As you see, I have defined the primary key task, as association key (association-key="true"), that references to the relation task, while that relation references to the field task_id. That's all, and please note, the primary key has not some generator at all (strategy="NONE").

You can use it only with relations Many-To-One and One-To-One.

More about identity through primary keys: https://www.doctrine-project.org/projects/doctrine-orm/en/2.7/tutorials/composite-primary-keys.html#identity-through-foreign-entities