Composite and Foreign Keys as Primary Key¶
Doctrine ORM supports composite primary keys natively. Composite keys are a very powerful relational database concept and we took good care to make sure Doctrine ORM supports as many of the composite primary key use-cases. For Doctrine ORM composite keys of primitive data-types are supported, even foreign keys as primary keys are supported.
This tutorial shows how the semantics of composite primary keys work and how they map to the database.
General Considerations¶
Every entity with a composite key cannot use an id generator other than “NONE”. That means
the ID fields have to have their values set before you call EntityManager#persist($entity)
.
Primitive Types only¶
You can have composite keys as long as they only consist of the primitive types
integer
and string
. Suppose you want to create a database of cars and use the model-name
and year of production as primary keys:
Now you can use this entity:
<?php
namespace VehicleCatalogue\Model;
// $em is the EntityManager
$car = new Car("Audi A8", 2010);
$em->persist($car);
$em->flush();
And for querying you can use arrays to both DQL and EntityRepositories:
<?php
namespace VehicleCatalogue\Model;
// $em is the EntityManager
$audi = $em->find("VehicleCatalogue\Model\Car", array("name" => "Audi A8", "year" => 2010));
$dql = "SELECT c FROM VehicleCatalogue\Model\Car c WHERE c.id = ?1";
$audi = $em->createQuery($dql)
->setParameter(1, ["name" => "Audi A8", "year" => 2010])
->getSingleResult();
You can also use this entity in associations. Doctrine will then generate two foreign keys one for name
and to year
to the related entities.
Note
This example shows how you can nicely solve the requirement for existing
values before EntityManager#persist()
: By adding them as mandatory values for the constructor.
Identity through foreign Entities¶
There are tons of use-cases where the identity of an Entity should be determined by the entity of one or many parent entities.
Dynamic Attributes of an Entity (for example Article). Each Article has many attributes with primary key “article_id” and “attribute_name”.
エンティティの動的属性 (記事など)。各記事には、主キー「article_id」と「attribute_name」を持つ多くの属性があります。Address object of a Person, the primary key of the address is “user_id”. This is not a case of a composite primary key, but the identity is derived through a foreign entity and a foreign key.
Person の Address オブジェクトで、アドレスの主キーは「user_id」です。これは複合主キーの場合ではありませんが、ID は外部エンティティと外部キーによって導出されます。Join Tables with metadata can be modelled as Entity, for example connections between two articles with a little description and a score.
メタデータを含む結合テーブルは、エンティティとしてモデル化できます。たとえば、簡単な説明とスコアを持つ 2 つの記事間の接続です。
The semantics of mapping identity through foreign entities are easy:
Only allowed on Many-To-One or One-To-One associations.
多対 1 または 1 対 1 の関連付けでのみ許可されます。Plug an
#[Id]
attribute onto every association.#[Id] 属性をすべての関連付けに接続します。Set an attribute
association-key
with the field name of the association in XML.XML で関連付けのフィールド名を使用して属性 association-key を設定します。Set a key
associationKey:
with the field name of the association in YAML.YAML のアソシエーションのフィールド名でキー associationKey: を設定します。
Use-Case 1: Dynamic Attributes¶
We keep up the example of an Article with arbitrary attributes, the mapping looks like this:
Use-Case 2: Simple Derived Identity¶
Sometimes you have the requirement that two objects are related by a One-To-One association and that the dependent class should re-use the primary key of the class it depends on. One good example for this is a user-address relationship:
Use-Case 3: Join-Table with Metadata¶
In the classic order product shop example there is the concept of the order item which contains references to order and product and additional data such as the amount of products purchased and maybe even the current price.
<?php
use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
#[Entity]
class Order
{
#[Id, Column, GeneratedValue]
private int|null $id = null;
/** @var ArrayCollection<int, OrderItem> */
#[OneToMany(targetEntity: OrderItem::class, mappedBy: 'order')]
private Collection $items;
#[Column]
private bool $paid = false;
#[Column]
private bool $shipped = false;
#[Column]
private DateTime $created;
public function __construct(
#[ManyToOne(targetEntity: Customer::class)]
private Customer $customer,
) {
$this->items = new ArrayCollection();
$this->created = new DateTime("now");
}
}
#[Entity]
class Product
{
#[Id, Column, GeneratedValue]
private int|null $id = null;
#[Column]
private string $name;
#[Column]
private int $currentPrice;
public function getCurrentPrice(): int
{
return $this->currentPrice;
}
}
#[Entity]
class OrderItem
{
#[Id, ManyToOne(targetEntity: Order::class)]
private Order|null $order = null;
#[Id, ManyToOne(targetEntity: Product::class)]
private Product|null $product = null;
#[Column]
private int $amount = 1;
#[Column]
private int $offeredPrice;
public function __construct(Order $order, Product $product, int $amount = 1)
{
$this->order = $order;
$this->product = $product;
$this->offeredPrice = $product->getCurrentPrice();
}
}
Performance Considerations¶
Using composite keys always comes with a performance hit compared to using entities with a simple surrogate key. This performance impact is mostly due to additional PHP code that is necessary to handle this kind of keys, most notably when using derived identifiers.
On the SQL side there is not much overhead as no additional or unexpected queries have to be executed to manage entities with derived foreign keys.