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.

Doctrine ORM は複合主キーをネイティブにサポートします。複合キーは非常に強力なリレーショナル データベースの概念であり、Doctrine ORM が複合主キーのユースケースをできるだけ多くサポートするように細心の注意を払いました.Doctrine ORM では、プリミティブ データ型の複合キーがサポートされ、主キーとしての外部キーもサポートされます.

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).

複合キーを持つすべてのエンティティは、「NONE」以外の ID ジェネレーターを使用できません。つまり、EntityManager#persist($entity) を呼び出す前に、ID フィールドに値を設定する必要があります。

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:

また、クエリを実行するために、DQL と 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.

このエンティティは関連付けでも使用できます。次に Doctrine は、関連するエンティティに対して name と to year の 2 つの外部キーを生成します。

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.

この例は、EntityManager#persist() の前に既存の値の要件を適切に解決する方法を示しています: コンストラクターの必須値としてそれらを追加することによって。

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.

エンティティの ID を 1 つまたは複数の親エンティティのエンティティによって決定する必要があるユースケースは数多くあります。

  • 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:

外部エンティティを介した ID のマッピングのセマンティクスは簡単です。

  • 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:

場合によっては、2 つのオブジェクトが 1 対 1 の関連付けによって関連付けられている必要があり、依存するクラスが依存するクラスの主キーを再利用する必要がある場合があります。これの 1 つの良い例は、ユーザーとアドレスの関係です。

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.

複合キーを使用すると、単純な代理キーを持つエンティティを使用する場合と比較して、常にパフォーマンスが低下します。このパフォーマンスへの影響は、ほとんどの場合、この種のキーを処理するために必要な追加の PHP コードが原因であり、特に派生識別子を使用する場合に顕著です。

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.

SQL 側では、派生した外部キ​​ーを持つエンティティを管理するために追加のクエリや予期しないクエリを実行する必要がないため、オーバーヘッドはあまりありません。

Table Of Contents

Previous topic

Extra Lazy Associations

エクストラ レイジー アソシエーション

Next topic

Ordering To-Many Associations

対多アソシエーションの順序付け

This Page

Fork me on GitHub