4. Basic Mapping

This guide explains the basic mapping of entities and properties. After working through this guide you should know:

このガイドでは、エンティティとプロパティの基本的なマッピングについて説明します。このガイドを読み終えたら、次のことを知っておく必要があります。

  • How to create PHP objects that can be saved to the database with Doctrine;

    Doctrine でデータベースに保存できる PHP オブジェクトを作成する方法;

  • How to configure the mapping between columns on tables and properties on entities;

    テーブルの列とエンティティのプロパティ間のマッピングを構成する方法。

  • What Doctrine mapping types are;

    Doctrine マッピング タイプとは;

  • Defining primary keys and how identifiers are generated by Doctrine;

    主キーの定義と、Doctrine による識別子の生成方法。

  • How quoting of reserved symbols works in Doctrine.

    Doctrine で予約済みシンボルの引用がどのように機能するか。

Mapping of associations will be covered in the next chapter on Association Mapping.

アソシエーションのマッピングについては、アソシエーション マッピングに関する次の章で説明します。

4.1. Creating Classes for the Database

Every PHP object that you want to save in the database using Doctrine is called an Entity. The term “Entity” describes objects that have an identity over many independent requests. This identity is usually achieved by assigning a unique identifier to an entity. In this tutorial the following Message PHP class will serve as the example Entity:

Doctrine を使用してデータベースに保存するすべての PHP オブジェクトはエンティティと呼ばれます。 「エンティティ」という用語は、多くの独立した要求に対して ID を持つオブジェクトを表します。この ID は通常、一意の識別子をエンティティに割り当てることによって実現されます。このチュートリアルでは、次のメッセージ PHP クラスがエンティティの例として機能します。

<?php
class Message
{
    private $id;
    private $text;
    private $postedAt;
}

Because Doctrine is a generic library, it only knows about your entities because you will describe their existence and structure using mapping metadata, which is configuration that tells Doctrine how your entity should be stored in the database. The documentation will often speak of “mapping something”, which means writing the mapping metadata that describes your entity.

Doctrine は一般的なライブラリであるため、マッピング メタデータを使用して存在と構造を記述するため、yourentities についてのみ認識します。これは、yourentity をデータベースに格納する方法を Doctrine に指示する構成です。ドキュメントでは、エンティティを説明するマッピング メタデータを記述することを意味する "何かをマッピングする" とよく言われます。

Doctrine provides several different ways to specify object-relational mapping metadata:

Doctrine は、オブジェクト リレーショナル マッピング メタデータを指定するいくつかの異なる方法を提供します。

will be removed in doctrine/orm 3.0)

doctrine/orm 3.0 で削除されます)

  • YAML (deprecated and will be removed in doctrine/orm 3.0.)

    YAML (非推奨であり、doctrine/orm 3.0 で削除されます。)

This manual will usually show mapping metadata via attributes, though many examples also show the equivalent configuration in annotations, YAML and XML.

このマニュアルでは通常、属性によるメタデータのマッピングを示しますが、多くの例では、アノテーション、YAML、および XML での同等の構成も示しています。

Note

ノート

All metadata drivers perform equally. Once the metadata of a class has been read from the source (attributes, annotations, XML, etc.) it is stored in an instance of the Doctrine\ORM\Mapping\ClassMetadata class which are stored in the metadata cache. If you’re not using a metadata cache (not recommended!) then the XML driver is the fastest.

すべてのメタデータ ドライバーは同等に機能します。クラスのメタデータがソース (属性、注釈、XML など) から読み取られると、メタデータ キャッシュに格納される Doctrine\ORM\Mapping\ClassMetadata クラスのインスタンスに格納されます。メタデータ キャッシュ (お勧めしません!) の場合、XML ドライバーが最も高速です。

Marking our Message class as an entity for Doctrine is straightforward:

Message クラスを Doctrine のエンティティとしてマークするのは簡単です:

With no additional information, Doctrine expects the entity to be saved into a table with the same name as the class in our case Message. You can change this by configuring information about the table:

追加情報がない場合、Doctrine はエンティティが Message の場合のクラスと同じ名前のテーブルに保存されることを期待します。これは、テーブルに関する情報を構成することで変更できます。

Now the class Message will be saved and fetched from the table message.

これで、クラス Message が保存され、テーブル メッセージから取得されます。

4.2. Property Mapping

The next step is mapping its properties to columns in the table.

次のステップは、そのプロパティをテーブルの列にマッピングすることです。

To configure a property use the Column attribute. The type argument specifies the Doctrine Mapping Type to use for the field. If the type is not specified, string is used as the default.

プロパティを構成するには、Column 属性を使用します。 type引数は、フィールドに使用するDoctrine Mapping Typeを指定します。タイプが指定されていない場合、文字列がデフォルトとして使用されます。

When we don’t explicitly specify a column name via the name option, Doctrine assumes the field name is also the column name. So in this example:

name オプションで列名を明示的に指定しない場合、Doctrine はフィールド名も列名であると想定します。したがって、この例では:

  • the id property will map to the column id using the type integer;

    id プロパティは、整数型を使用して列 id にマップされます。

  • the text property will map to the column text with the default mapping type string;

    text プロパティは、デフォルトのマッピング タイプ文字列で列テキストにマッピングされます。

  • the postedAt property will map to the posted_at column with the datetime type.

    postedAt プロパティは、datetime タイプの posted_at 列にマップされます。

Here is a complete list of ``Column``s attributes (all optional):

以下は ``Column`` 属性の完全なリストです (すべてオプション):

  • type (default: ‘string’): The mapping type to use for the column.

    type (デフォルト: 'string'): 列に使用するマッピング タイプ。

  • name (default: name of property): The name of the column in the database.

    name (デフォルト: プロパティの名前): データベース内の列の名前。

  • length (default: 255): The length of the column in the database. Applies only if a string-valued column is used.

    length (デフォルト: 255): データベース内の列の長さ。文字列値の列が使用されている場合にのみ適用されます。

  • unique (default: false): Whether the column is a unique key.

    unique (デフォルト: false): 列が一意のキーかどうか。

  • nullable (default: false): Whether the column is nullable.

    nullable (デフォルト: false): 列が null 可能かどうか。

  • insertable (default: true): Whether the column should be inserted.

    insertable (デフォルト: true): 列を挿入するかどうか。

  • updatable (default: true): Whether the column should be updated.

    updateable (デフォルト: true): 列を更新するかどうか。

  • enumType (requires PHP 8.1 and doctrine/orm 2.11): The PHP enum class name to convert the database value into.

    enumType (PHP 8.1 および doctrine/orm 2.11 が必要): データベース値を変換する PHP enum クラス名。

  • precision (default: 0): The precision for a decimal (exact numeric) column (applies only for decimal column), which is the maximum number of digits that are stored for the values.

    精度 (デフォルト: 0): 10 進数 (正確な数値) 列の精度 (10 進数列にのみ適用されます)。これは、値に対して格納される最大桁数です。

  • scale (default: 0): The scale for a decimal (exact numeric) column (applies only for decimal column), which represents the number of digits to the right of the decimal point and must not be greater than precision.

    scale (デフォルト: 0): 10 進数 (正確な数値) 列の位取り (10 進数列にのみ適用)。これは小数点以下の桁数を表し、精度を超えてはなりません。

  • columnDefinition: Allows to define a custom DDL snippet that is used to create the column. Warning: This normally confuses the SchemaTool to always detect the column as changed.

    columnDefinition: 列の作成に使用される customDDL スニペットを定義できます。警告: これは通常、SchemaTool を混乱させ、常に列が変更されていることを検出します。

  • options: Key-value pairs of options that get passed to the underlying database platform when generating DDL statements.

    options: DDL ステートメントの生成時に基礎となるデータベース プラットフォームに渡されるオプションのキーと値のペア。

4.2.1. PHP Types Mapping

New in version 2.9.

バージョン 2.9 の新機能。

The column types can be inferred automatically from PHP’s property types. However, when the property type is nullable this has no effect on the nullable Column attribute.

列の型は、PHP のプロパティの型から自動的に推測できます。ただし、プロパティの型が null 許容の場合、これは null 許容の Column 属性には影響しません。

These are the “automatic” mapping rules:

これらは「自動」マッピング ルールです。

PHP property type

PHP プロパティ タイプ

Doctrine column type

教義列タイプ

DateInterval

日付間隔

Types::DATEINTERVAL

タイプ::DATEINTERVAL

DateTime

日付時刻

Types::DATETIME_MUTABLE

タイプ::DATETIME_MUTABLE

DateTimeImmutable

DateTime不変

Types::DATETIME_IMMUTABLE

タイプ::DATETIME_IMMUTABLE

array

配列

Types::JSON

タイプ::JSON

bool

ブール

Types::BOOLEAN

タイプ::ブール値

float

浮く

Types::FLOAT

タイプ::FLOAT

int

整数

Types::INTEGER

タイプ::INTEGER

Any other type

その他のタイプ

Types::STRING

タイプ::STRING

As of version 2.11 Doctrine can also automatically map typed properties using a PHP 8.1 enum to set the right type and enumType.

バージョン 2.11 以降、Doctrine は PHP 8.1 列挙型を使用して型付きプロパティを自動的にマップし、適切な型と enumType を設定することもできます。

New in version 2.14.

バージョン 2.14 の新機能。

Since version 2.14 you can specify custom typed field mapping between PHP type and DBAL type using Configuration and a custom Doctrine\ORM\Mapping\TypedFieldMapper implementation.

バージョン 2.14 以降、Configuration とカスタム Doctrine\ORM\Mapping\TypedFieldMapper 実装を使用して、PHP 型と DBAL 型の間のカスタム型付きフィールド マッピングを指定できます。

Read more about TypedFieldMapper.

TypedFieldMapper の詳細を参照してください。

4.3. Doctrine Mapping Types

The type option used in the @Column accepts any of the existing Doctrine types or even your own custom types. A Doctrine type defines the conversion between PHP and SQL types, independent from the database vendor you are using. All Mapping Types that ship with Doctrine are fully portable between the supported database systems.

@Column で使用される type オプションは、既存のDoctrine タイプまたは独自のカスタム タイプのいずれかを受け入れます。 Doctrine 型は、使用しているデータベース ベンダーに関係なく、PHP と SQL 型の間の変換を定義します。 Doctrine に同梱されているすべてのマッピング タイプは、サポートされているデータベース システム間で完全に移植可能です。

As an example, the Doctrine Mapping Type string defines the mapping from a PHP string to a SQL VARCHAR (or VARCHAR2 etc. depending on the RDBMS brand). Here is a quick overview of the built-in mapping types:

例として、Doctrine Mapping Type 文字列は、PHP 文字列から SQL VARCHAR (または RDBMS ブランドに応じて VARCHAR2 など) へのマッピングを定義します。組み込みのマッピング タイプの概要を次に示します。

  • string: Type that maps a SQL VARCHAR to a PHP string.

    string: SQL VARCHAR を PHP 文字列にマップする型。

  • integer: Type that maps a SQL INT to a PHP integer.

    integer: SQL INT を PHP 整数にマップする型。

  • smallint: Type that maps a database SMALLINT to a PHP integer.

    smallint: データベースの SMALLINT を PHPinteger にマップする型。

  • bigint: Type that maps a database BIGINT to a PHP string.

    bigint: データベース BIGINT を PHP 文字列にマップする型。

  • boolean: Type that maps a SQL boolean or equivalent (TINYINT) to a PHP boolean.

    boolean: SQL ブール値または同等の値 (TINYINT) を PHP ブール値にマップする型。

  • decimal: Type that maps a SQL DECIMAL to a PHP string.

    decimal: SQL DECIMAL を PHP 文字列にマップする型。

  • date: Type that maps a SQL DATETIME to a PHP DateTime object.

    date: SQL DATETIME を PHP DateTime オブジェクトにマップする型。

  • time: Type that maps a SQL TIME to a PHP DateTime object.

    time: SQL TIME を PHP DateTime オブジェクトにマップする型。

  • datetime: Type that maps a SQL DATETIME/TIMESTAMP to a PHP DateTime object.

    datetime: SQL DATETIME/TIMESTAMP を PHPDateTime オブジェクトにマップする型。

  • datetimetz: Type that maps a SQL DATETIME/TIMESTAMP to a PHP DateTime object with timezone.

    datetimetz: SQL DATETIME/TIMESTAMP をタイムゾーン付きの PHPDateTime オブジェクトにマップする型。

  • text: Type that maps a SQL CLOB to a PHP string.

    text: SQL CLOB を PHP 文字列にマップする型。

  • object: Type that maps a SQL CLOB to a PHP object using serialize() and unserialize()

    object: SQL CLOB を PHP オブジェクトにマップする型で、serialize() と unserialize() を使用します

  • array: Type that maps a SQL CLOB to a PHP array using serialize() and unserialize()

    array: SQL CLOB を PHP 配列にマップする型で、serialize() と unserialize() を使用します

  • simple_array: Type that maps a SQL CLOB to a PHP array using implode() and explode(), with a comma as delimiter. IMPORTANT Only use this type if you are sure that your values cannot contain a “,”.

    simple_array: implode() と destroy() を使用して SQL CLOB を PHP 配列にマップする型で、コンマを区切り文字として使用します。重要値に「,」を含めることができないことが確実な場合にのみ、このタイプを使用してください。

  • json_array: Type that maps a SQL CLOB to a PHP array using json_encode() and json_decode()

    json_array: json_encode() および json_decode() を使用して SQL CLOB を PHP 配列にマップする型

  • float: Type that maps a SQL Float (Double Precision) to a PHP double. IMPORTANT: Works only with locale settings that use decimal points as separator.

    float: SQL Float (倍精度) を PHP の double にマップする型。重要: 区切り記号として小数点を使用するロケール設定でのみ機能します。

  • guid: Type that maps a database GUID/UUID to a PHP string. Defaults to varchar but uses a specific type if the platform supports it.

    guid: データベース GUID/UUID を PHP 文字列にマップする型。デフォルトは varchar ですが、プラットフォームがサポートしている場合は特定の型を使用します。

  • blob: Type that maps a SQL BLOB to a PHP resource stream

    blob: SQL BLOB を PHP リソース ストリームにマップする型

A cookbook article shows how to define your own custom mapping types.

クックブックの記事では、独自のカスタム マッピング タイプを定義する方法を示しています。

Note

ノート

DateTime and Object types are compared by reference, not by value. Doctrine updates this values if the reference changes and therefore behaves as if these objects are immutable value objects.

DateTime 型と Object 型は、値ではなく参照によって比較されます。参照が変更された場合、Doctrine はこの値を更新するため、これらのオブジェクトが不変の値オブジェクトであるかのように動作します。

Warning

警告

All Date types assume that you are exclusively using the default timezone set by date_default_timezone_set() or by the php.ini configuration date.timezone. Working with different timezones will cause troubles and unexpected behavior.

すべての Date タイプは、date_default_timezone_set() または php.ini 設定 date.timezone によって設定されたデフォルトのタイムゾーンのみを使用していることを前提としています。異なるタイムゾーンで作業すると、トラブルや予期しない動作が発生する可能性があります。

If you need specific timezone handling you have to handle this in your domain, converting all the values back and forth from UTC. There is also a cookbook entry on working with datetimes that gives hints for implementing multi timezone applications.

特定のタイムゾーン処理が必要な場合は、ドメイン内でこれを処理し、すべての値を UTC から前後に変換する必要があります。複数のタイムゾーン アプリケーションを実装するためのヒントを提供する日付時刻の操作に関するクックブック エントリもあります。

4.4. Identifiers / Primary Keys

Every entity class must have an identifier/primary key. You can select the field that serves as the identifier with the #[Id] attribute.

すべてのエンティティ クラスには、識別子/主キーが必要です。 #[Id]属性で識別子となるフィールドを選択できます。

In most cases using the automatic generator strategy (#[GeneratedValue]) is what you want. It defaults to the identifier generation mechanism your current database vendor prefers: AUTO_INCREMENT with MySQL, sequences with PostgreSQL and Oracle and so on.

ほとんどの場合、自動生成戦略 (#[GeneratedValue]) を使用することをお勧めします。これは、現在のデータベース ベンダーが好む識別子生成メカニズムにデフォルト設定されます。MySQL では AUTO_INCREMENT、PostgreSQL および Oracle ではシーケンスなどです。

The previous example showed how to use the default identifier generation strategy without knowing the underlying database with the AUTO-detection strategy. It is also possible to specify the identifier generation strategy more explicitly, which allows you to make use of some additional features.

前の例では、基礎となるデータベースを知らずにデフォルトの識別子生成戦略を使用する方法を AUTO 検出戦略で示しました。識別子の生成方法をより明示的に指定することもできます。これにより、いくつかの追加機能を利用できます。

Here is the list of possible generation strategies:

可能な生成戦略のリストは次のとおりです。

  • AUTO (default): Tells Doctrine to pick the strategy that is preferred by the used database platform. The preferred strategies are IDENTITY for MySQL, SQLite, MsSQL and SQL Anywhere and SEQUENCE for Oracle and PostgreSQL. This strategy provides full portability.

    AUTO (デフォルト): Doctrine に、使用されているデータベース プラットフォームで優先される戦略を選択するように指示します。推奨される戦略は、MySQL、SQLite、MsSQL、および SQL Anywhere の IDENTITY と、Oracle および PostgreSQL の SEQUENCE です。この戦略は、完全な移植性を提供します。

  • SEQUENCE: Tells Doctrine to use a database sequence for ID generation. This strategy does currently not provide full portability. Sequences are supported by Oracle, PostgreSql and SQL Anywhere.

    SEQUENCE: ID生成にデータベースシーケンスを使用するようDoctrineに指示します。この戦略は現在、完全な移植性を提供していません。シーケンスは、Oracle、PostgreSql、SQL Anywhere でサポートされています。

  • IDENTITY: Tells Doctrine to use special identity columns in the database that generate a value on insertion of a row. This strategy does currently not provide full portability and is supported by the following platforms: MySQL/SQLite/SQL Anywhere (AUTO_INCREMENT), MSSQL (IDENTITY) and PostgreSQL (SERIAL).

    IDENTITY: 行の挿入時に値を生成する、データベース内の特別な ID 列を使用するよう Doctrine に指示します。この戦略は現在、完全な移植性を提供しておらず、次のプラットフォームでサポートされています: MySQL/SQLite/SQL Anywhere (AUTO_INCREMENT)、MSSQL (IDENTITY)、および PostgreSQL (SERIAL)。

  • UUID (deprecated): Tells Doctrine to use the built-in Universally Unique Identifier generator. This strategy provides full portability.

    UUID (非推奨): Doctrine に組み込みの UniversallyUnique Identifier ジェネレーターを使用するように指示します。この戦略は、完全な移植性を提供します。

  • NONE: Tells Doctrine that the identifiers are assigned (and thus generated) by your code. The assignment must take place before a new entity is passed to EntityManager#persist. NONE is the same as leaving off the #[GeneratedValue] entirely.

    NONE: 識別子がコードによって割り当てられている (したがって生成されている) ことを Doctrine に伝えます。新しいエンティティが EntityManager#persist に渡される前に、割り当てを行う必要があります。 NONE は #[GeneratedValue] を完全に除外することと同じです。

  • CUSTOM: With this option, you can use the #[CustomIdGenerator] attribute. It will allow you to pass a class of your own to generate the identifiers.

    CUSTOM: このオプションでは、#[CustomIdGenerator] 属性を使用できます。独自のクラスを渡して識別子を生成できます。

The Sequence Generator can currently be used in conjunction with Oracle or Postgres and allows some additional configuration options besides specifying the sequence’s name:

シーケンス ジェネレーターは現在、Oracle または Postgres と組み合わせて使用​​でき、シーケンスの名前を指定する以外に、いくつかの追加の構成オプションを使用できます。

The initial value specifies at which value the sequence should start.

初期値は、シーケンスを開始する値を指定します。

The allocationSize is a powerful feature to optimize INSERT performance of Doctrine. The allocationSize specifies by how much values the sequence is incremented whenever the next value is retrieved. If this is larger than 1 (one) Doctrine can generate identifier values for the allocationSizes amount of entities. In the above example with allocationSize=100 Doctrine ORM would only need to access the sequence once to generate the identifiers for 100 new entities.

allocationSize は、Doctrine の INSERT パフォーマンスを最適化するための強力な機能です。 allocationSize は、次の値が取得されるたびにシーケンスがインクリメントされる値の量を指定します。これが 1 より大きい場合、Doctrine は、allocationSizes 個のエンティティの識別子の値を生成できます。上の例では、allocationSize=100 で、Doctrine ORM は 100 個の新しいエンティティの識別子を生成するためにシーケンスに 1 回アクセスするだけで済みます。

The default allocationSize for a @SequenceGenerator is currently 10.

@SequenceGenerator のデフォルトの allocationSize は現在 10 です。

Caution

注意

The allocationSize is detected by SchemaTool and transformed into an “INCREMENT BY “ clause in the CREATE SEQUENCE statement. For a database schema created manually (and not SchemaTool) you have to make sure that the allocationSize configuration option is never larger than the actual sequences INCREMENT BY value, otherwise you may get duplicate keys.

allocationSize は SchemaTool によって検出され、CREATE SEQUENCE ステートメントの「INCREMENT BY」句に変換されます。手動で作成された (SchemaTool ではない) データベース スキーマの場合、allocationSize 構成オプションが実際のシーケンスの INCREMENT BY 値よりも大きくならないようにする必要があります。そうしないと、キーが重複する可能性があります。

Note

ノート

It is possible to use strategy=”AUTO” and at the same time specifying a @SequenceGenerator. In such a case, your custom sequence settings are used in the case where the preferred strategy of the underlying platform is SEQUENCE, such as for Oracle and PostgreSQL.

strategy="AUTO" を使用し、同時に @SequenceGenerator を指定することができます。このような場合、Oracle や PostgreSQL など、基盤となるプラットフォームの優先戦略が SEQUENCE である場合にカスタム シーケンス設定が使用されます。

With Doctrine ORM you can use composite primary keys, using #[Id] on more than one column. Some restrictions exist opposed to using a single identifier in this case: The use of the #[GeneratedValue] attribute is not supported, which means you can only use composite keys if you generate the primary key values yourself before calling EntityManager#persist() on the entity.

Doctrine ORM を使用すると、複数の列で #[Id] を使用して複合主キーを使用できます。この場合、単一の識別子を使用するのではなく、いくつかの制限があります: #[GeneratedValue] 属性の使用はサポートされていません。つまり、エンティティで EntityManager#persist() を呼び出す前に、主キーの値を自分で生成する場合にのみ、複合キーを使用できます。

More details on composite primary keys are discussed in a dedicated tutorial.

複合主キーの詳細については、専用のチュートリアルで説明しています。

4.5. Quoting Reserved Words

Sometimes it is necessary to quote a column or table name because of reserved word conflicts. Doctrine does not quote identifiers automatically, because it leads to more problems than it would solve. Quoting tables and column names needs to be done explicitly using ticks in the definition.

予約語の競合のために、列またはテーブル名を引用符で囲む必要がある場合があります。 Doctrine は識別子を自動的に引用しません。テーブル名と列名の引用は、定義でティックを使用して明示的に行う必要があります。

<?php

#[Column(name: '`number`', type: 'integer')]
private $number;

Doctrine will then quote this column name in all SQL statements according to the used database platform.

Doctrine は、使用されているデータベース プラットフォームに従って、すべての SQL ステートメントでこの列名を引用します。

Warning

警告

Identifier Quoting does not work for join column names or discriminator column names unless you are using a custom QuoteStrategy.

カスタム QuoteStrategy を使用していない限り、識別子の引用は、結合列名または識別子列名に対して機能しません。

For more control over column quoting the Doctrine\ORM\Mapping\QuoteStrategy interface was introduced in ORM. It is invoked for every column, table, alias and other SQL names. You can implement the QuoteStrategy and set it by calling Doctrine\ORM\Configuration#setQuoteStrategy().

列の引用をより詳細に制御するために、Doctrine\ORM\Mapping\QuoteStrategy インターフェイスが ORM に導入されました。すべての列、テーブル、エイリアス、およびその他の SQL 名に対して呼び出されます。 QuoteStrategy を実装し、Doctrine\ORM\Configuration#setQuoteStrategy() を呼び出すことで設定できます。

The ANSI Quote Strategy was added, which assumes quoting is not necessary for any SQL name. You can use it with the following code:

ANSI Quote Strategy が追加されました。これは、SQL 名に引用符が必要ないことを前提としています。次のコードで使用できます。

<?php
use Doctrine\ORM\Mapping\AnsiQuoteStrategy;

$configuration->setQuoteStrategy(new AnsiQuoteStrategy());

Table Of Contents

Previous topic

3. Frequently Asked Questions

3. よくある質問

Next topic

5. Association Mapping

5. アソシエーション マッピング

This Page

Fork me on GitHub