21. XML Mapping

The XML mapping driver enables you to provide the ORM metadata in form of XML documents.

XML マッピング ドライバーを使用すると、XML ドキュメントの ORM メタデータ情報を提供できます。

The XML driver is backed by an XML Schema document that describes the structure of a mapping document. The most recent version of the XML Schema document is available online at https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd. The most convenient way to work with XML mapping files is to use an IDE/editor that can provide code-completion based on such an XML Schema document. The following is an outline of a XML mapping document with the proper xmlns/xsi setup for the latest code in trunk.

XML ドライバーは、マッピング ドキュメントの構造を記述する XML スキーマ ドキュメントによって支えられています。 XML スキーマ ドキュメントの最新バージョンは、https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd でオンラインで入手できます。このような XML スキーマ ドキュメントに基づいてコード補完を提供できます。以下は、trunk の最新コードの適切な xmlns/xsisetup を含む XML マッピング ドキュメントの概要です。

<doctrine-mapping xmlns="https://doctrine-project.org/schemas/orm/doctrine-mapping"
      xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="https://doctrine-project.org/schemas/orm/doctrine-mapping
                          https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

    ...

</doctrine-mapping>

The XML mapping document of a class is loaded on-demand the first time it is requested and subsequently stored in the metadata cache. In order to work, this requires certain conventions:

クラスの XML マッピング ドキュメントは、最初に要求されたときにオンデマンドで読み込まれ、その後メタデータ キャッシュに格納されます。これを機能させるには、次の規則が必要です。

  • Each entity/mapped superclass must get its own dedicated XML mapping document.

    各エンティティ/マップされたスーパークラスは、専用の XML マッピング ドキュメントを取得する必要があります。

  • The name of the mapping document must consist of the fully qualified name of the class, where namespace separators are replaced by dots (.). For example an Entity with the fully qualified class-name “MyProject” would require a mapping file “MyProject.Entities.User.dcm.xml” unless the extension is changed.

    マッピング ドキュメントの名前は、クラスの完全修飾名で構成する必要があります。名前空間の区切り文字はドット (.) に置き換えられます。たとえば、拡張子が変更されない限り、完全修飾クラス名「MyProject」を持つエンティティには、マッピング ファイル「MyProject.Entities.User.dcm.xml」が必要です。

  • All mapping documents should get the extension “.dcm.xml” to identify it as a Doctrine mapping file. This is more of a convention and you are not forced to do this. You can change the file extension easily enough.

    Doctrine マッピング ファイルであることを識別するために、すべてのマッピング ドキュメントに拡張子「.dcm.xml」を付ける必要があります。これは慣習的なものであり、これを強制されるものではありません。ファイル拡張子は簡単に変更できます。

<?php
$driver->setFileExtension('.xml');

It is recommended to put all XML mapping documents in a single folder but you can spread the documents over several folders if you want to. In order to tell the XmlDriver where to look for your mapping documents, supply an array of paths as the first argument of the constructor, like this:

すべての XML マッピング ドキュメントを 1 つのフォルダーに配置することをお勧めしますが、必要に応じて複数のフォルダーにドキュメントを分散させることもできます。マッピング ドキュメントを検索する場所を XmlDriver に指示するには、次のように、コンストラクターの最初の引数としてパスの配列を指定します。

<?php
$config = new \Doctrine\ORM\Configuration();
$driver = new \Doctrine\ORM\Mapping\Driver\XmlDriver(array('/path/to/files1', '/path/to/files2'));
$config->setMetadataDriverImpl($driver);

Warning

警告

Note that Doctrine ORM does not modify any settings for libxml, therefore, external XML entities may or may not be enabled or configured correctly. XML mappings are not XXE/XEE attack vectors since they are not related with user input, but it is recommended that you do not use external XML entities in your mapping files to avoid running into unexpected behaviour.

Doctrine ORM は libxml の設定を変更しないことに注意してください。したがって、外部 XML エンティティが有効または正しく設定されている場合とされていない場合があります。予期しない動作が発生しないように、マッピング ファイルで外部 XML エンティティを使用しないでください。

21.1. Simplified XML Driver

The Symfony project sponsored a driver that simplifies usage of the XML Driver. The changes between the original driver are:

Symfony プロジェクトは、XML ドライバーの使用を簡素化するドライバーを後援しました。元のドライバーとの変更点は次のとおりです。

  1. File Extension is .orm.xml

    ファイル拡張子は .orm.xml です

  2. Filenames are shortened, “MyProjectEntitiesUser” will become User.orm.xml

    ファイル名は短縮され、「MyProjectEntitiesUser」は User.orm.xml になります

  3. You can add a global file and add multiple entities in this file.

    グローバル ファイルを追加し、このファイルに複数のエンティティを追加できます。

Configuration of this client works a little bit different:

このクライアントの構成は少し異なります。

<?php
$namespaces = array(
    '/path/to/files1' => 'MyProject\Entities',
    '/path/to/files2' => 'OtherProject\Entities'
);
$driver = new \Doctrine\ORM\Mapping\Driver\SimplifiedXmlDriver($namespaces);
$driver->setGlobalBasename('global'); // global.orm.xml

21.1.1. Example

As a quick start, here is a small example document that makes use of several common elements:

クイック スタートとして、いくつかの一般的な要素を使用する小さなサンプル ドキュメントを次に示します。

// Doctrine.Tests.ORM.Mapping.User.dcm.xml
<?xml version="1.0" encoding="UTF-8"?>
<doctrine-mapping xmlns="https://doctrine-project.org/schemas/orm/doctrine-mapping"
      xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="https://doctrine-project.org/schemas/orm/doctrine-mapping
                          https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

    <entity name="Doctrine\Tests\ORM\Mapping\User" table="cms_users">

        <indexes>
            <index name="name_idx" columns="name"/>
            <index columns="user_email"/>
        </indexes>

        <unique-constraints>
            <unique-constraint columns="name,user_email" name="search_idx" />
        </unique-constraints>

        <lifecycle-callbacks>
            <lifecycle-callback type="prePersist" method="doStuffOnPrePersist"/>
            <lifecycle-callback type="prePersist" method="doOtherStuffOnPrePersistToo"/>
            <lifecycle-callback type="postPersist" method="doStuffOnPostPersist"/>
        </lifecycle-callbacks>

        <id name="id" type="integer" column="id">
            <generator strategy="AUTO"/>
            <sequence-generator sequence-name="tablename_seq" allocation-size="100" initial-value="1" />
        </id>

        <field name="name" column="name" type="string" length="50" nullable="true" unique="true" />
        <field name="email" column="user_email" type="string" column-definition="CHAR(32) NOT NULL" />

        <one-to-one field="address" target-entity="Address" inversed-by="user">
            <cascade><cascade-remove /></cascade>
            <join-column name="address_id" referenced-column-name="id" on-delete="CASCADE" on-update="CASCADE"/>
        </one-to-one>

        <one-to-many field="phonenumbers" target-entity="Phonenumber" mapped-by="user">
            <cascade>
                <cascade-persist/>
            </cascade>
            <order-by>
                <order-by-field name="number" direction="ASC" />
            </order-by>
        </one-to-many>

        <many-to-many field="groups" target-entity="Group">
            <cascade>
                <cascade-all/>
            </cascade>
            <join-table name="cms_users_groups">
                <join-columns>
                    <join-column name="user_id" referenced-column-name="id" nullable="false" unique="false" />
                </join-columns>
                <inverse-join-columns>
                    <join-column name="group_id" referenced-column-name="id" column-definition="INT NULL" />
                </inverse-join-columns>
            </join-table>
        </many-to-many>

    </entity>

</doctrine-mapping>

Be aware that class-names specified in the XML files should be fully qualified.

XML ファイルで指定されたクラス名は完全修飾されている必要があることに注意してください。

21.1.2. XML-Element Reference

The XML-Element reference explains all the tags and attributes that the Doctrine Mapping XSD Schema defines. You should read the Basic-, Association- and Inheritance Mapping chapters to understand what each of this definitions means in detail.

XML-Element リファレンスでは、Doctrine Mapping XSD スキーマが定義するすべてのタグと属性について説明しています。この各定義の意味を詳細に理解するには、基本、関連付け、および継承マッピングの章を読む必要があります。

21.2. Defining an Entity

Each XML Mapping File contains the definition of one entity, specified as the <entity /> element as a direct child of the <doctrine-mapping /> element:

各 XML マッピング ファイルには、要素の直接の子として要素として指定された 1 つのエンティティの定義が含まれています。

<doctrine-mapping>
    <entity name="MyProject\User" table="cms_users" schema="schema_name" repository-class="MyProject\UserRepository">
        <!-- definition here -->
    </entity>
</doctrine-mapping>

Required attributes:

必須属性:

  • name - The fully qualified class-name of the entity.

    name - エンティティの完全修飾クラス名。

Optional attributes:

オプションの属性:

  • table - The Table-Name to be used for this entity. Otherwise the Unqualified Class-Name is used by default.

    table - このエンティティに使用されるテーブル名。それ以外の場合、非修飾クラス名がデフォルトで使用されます。

  • repository-class - The fully qualified class-name of an alternative Doctrine\ORM\EntityRepository implementation to be used with this entity.

    repository-class - このエンティティで使用される別の Doctrine\ORM\EntityRepository 実装の完全修飾クラス名。

  • inheritance-type - The type of inheritance, defaults to none. A more detailed description follows in the Defining Inheritance Mappings section.

    inheritance-type - 継承のタイプで、デフォルトは none です。詳細な説明は、「継承マッピングの定義」セクションに続きます。

  • read-only - Specifies that this entity is marked as read only and not considered for change-tracking. Entities of this type can be persisted and removed though.

    読み取り専用 - このエンティティが読み取り専用としてマークされ、変更の追跡が考慮されないことを指定します。ただし、このタイプのエンティティは永続化および削除できます。

  • schema - The schema the table lies in, for platforms that support schemas

    schema - スキーマをサポートするプラットフォームの場合、テーブルがあるスキーマ

21.3. Defining Fields

Each entity class can contain zero to infinite fields that are managed by Doctrine. You can define them using the <field /> element as a children to the <entity /> element. The field element is only used for primitive types that are not the ID of the entity. For the ID mapping you have to use the <id /> element.

各エンティティ クラスには、Doctrine によって管理されるゼロから無限のフィールドを含めることができます。要素を要素の子として使用して、それらを定義できます。フィールド要素は、エンティティの ID ではないプリミティブ型にのみ使用されます。 ID マッピングには、要素を使用する必要があります。

<entity name="MyProject\User">

    <field name="name" type="string" length="50" />
    <field name="username" type="string" unique="true" />
    <field name="age" type="integer" nullable="true" />
    <field name="isActive" column="is_active" type="boolean" />
    <field name="weight" type="decimal" scale="5" precision="2" />
    <field name="login_count" type="integer" nullable="false">
        <options>
            <option name="comment">The number of times the user has logged in.</option>
            <option name="default">0</option>
        </options>
    </field>
</entity>

Required attributes:

必須属性:

  • name - The name of the Property/Field on the given Entity PHP class.

    name - 指定されたエンティティ PHPclass のプロパティ/フィールドの名前。

Optional attributes:

オプションの属性:

  • type - The Doctrine\DBAL\Types\Type name, defaults to “string”

    type - Doctrine\DBAL\Types\Type 名、デフォルトは「string」

  • column - Name of the column in the database, defaults to the field name.

    column - データベース内の列の名前。デフォルトはフィールド名です。

  • length - The length of the given type, for use with strings only.

    length - 文字列のみで使用する、指定された型の長さ。

  • unique - Should this field contain a unique value across the table? Defaults to false.

    unique - このフィールドには、テーブル全体で一意の値を含める必要がありますか?デフォルトは false です。

  • nullable - Should this field allow NULL as a value? Defaults to false.

    nullable - このフィールドは値として NULL を許可するか?デフォルトは false です。

  • insertable - Should this field be inserted? Defaults to true.

    insertable - このフィールドを挿入する必要がありますか?デフォルトは true です。

  • updatable - Should this field be updated? Defaults to true.

    updateable - このフィールドを更新する必要がありますか?デフォルトは true です。

  • generated - Enum of the values ALWAYS, INSERT, NEVER that determines if generated value must be fetched from database after INSERT or UPDATE. Defaults to “NEVER”.

    generated - INSERT または UPDATE の後に生成された値をデータベースから取得する必要があるかどうかを決定する ALWAYS、INSERT、NEVER の値の列挙。デフォルトは「NEVER」です。

  • version - Should this field be used for optimistic locking? Only works on fields with type integer or datetime.

    version - このフィールドを楽観的ロックに使用する必要がありますか?整数型または日時型のフィールドでのみ機能します。

  • scale - Scale of a decimal type.

    scale - 10 進数型のスケール。

  • precision - Precision of a decimal type.

    precision - 10 進数型の精度。

  • options - Array of additional options:

    options - 追加オプションの配列:

    • default - The default value to set for the column if no value is supplied.

      default - 値が指定されていない場合に列に設定するデフォルト値。

    • unsigned - Boolean value to determine if the column should be capable of representing only non-negative integers (applies only for integer column and might not be supported by all vendors).

      unsigned - 列が負でない整数のみを表すことができるかどうかを決定するブール値 (整数列にのみ適用され、すべてのベンダーでサポートされているとは限りません)。

    • fixed - Boolean value to determine if the specified length of a string column should be fixed or varying (applies only for string/binary column and might not be supported by all vendors).

      fixed - 文字列列の指定された長さが固定か可変かを決定するブール値 (文字列/バイナリ列にのみ適用され、すべてのベンダーでサポートされているわけではありません)。

    • comment - The comment of the column in the schema (might not be supported by all vendors).

      comment - スキーマ内の列のコメント (すべてのベンダーでサポートされているわけではありません)。

    • customSchemaOptions - Array of additional schema options which are mostly vendor specific.

      customSchemaOptions - ほとんどがベンダー固有の追加スキーマ オプションの配列。

  • column-definition - Optional alternative SQL representation for this column. This definition begin after the field-name and has to specify the complete column definition. Using this feature will turn this field dirty for Schema-Tool update commands at all times.

    column-definition - この列のオプションの代替 SQL 表現。この定義はフィールド名の後に始まり、完全な列定義を指定する必要があります。この機能を使用すると、スキーマ ツールの更新コマンドに対して常にこのフィールドがダーティになります。

Note

ノート

For more detailed information on each attribute, please refer to the DBAL Schema-Representation documentation.

各属性の詳細については、DBAL スキーマ表現のドキュメントを参照してください。

21.4. Defining Identity and Generator Strategies

An entity has to have at least one <id /> element. For composite keys you can specify more than one id-element, however surrogate keys are recommended for use with Doctrine ORM. The Id field allows to define properties of the identifier and allows a subset of the <field /> element attributes:

エンティティには少なくとも 1 つの要素が必要です。複合キーの場合、複数の id 要素を指定できますが、Doctrine ORM では代理キーを使用することをお勧めします。 Idfield を使用すると、識別子のプロパティを定義でき、要素属性のサブセットを使用できます。

<entity name="MyProject\User">
    <id name="id" type="integer" column="user_id" />
</entity>

Required attributes:

必須属性:

  • name - The name of the Property/Field on the given Entity PHP class.

    name - 指定されたエンティティ PHPclass のプロパティ/フィールドの名前。

  • type - The Doctrine\DBAL\Types\Type name, preferably “string” or “integer”.

    type - Doctrine\DBAL\Types\Type 名、できれば「文字列」または「整数」。

Optional attributes:

オプションの属性:

  • column - Name of the column in the database, defaults to the field name.

    column - データベース内の列の名前。デフォルトはフィールド名です。

Using the simplified definition above Doctrine will use no identifier strategy for this entity. That means you have to manually set the identifier before calling EntityManager#persist($entity). This is the so called NONE strategy.

上記の簡略化された定義を使用すると、Doctrine はこのエンティティに対して noidentifier 戦略を使用します。つまり、EntityManager#persist($entity) を呼び出す前に、識別子を手動で設定する必要があります。これがいわゆるNONE戦略です。

If you want to switch the identifier generation strategy you have to nest a <generator /> element inside the id-element. This of course only works for surrogate keys. For composite keys you always have to use the NONE strategy.

識別子生成戦略を切り替えたい場合は、id 要素内に要素をネストする必要があります。もちろん、これは代理キーに対してのみ機能します。複合キーの場合は、常に NONE 戦略を使用する必要があります。

<entity name="MyProject\User">
    <id name="id" type="integer" column="user_id">
        <generator strategy="AUTO" />
    </id>
</entity>

The following values are allowed for the <generator /> strategy attribute:

次の値は、strategy 属性に使用できます。

  • AUTO - Automatic detection of the identifier strategy based on the preferred solution of the database vendor.

    AUTO - データベース ベンダーの推奨ソリューションに基づく識別子戦略の自動検出。

  • IDENTITY - Use of a IDENTIFY strategy such as Auto-Increment IDs available to Doctrine AFTER the INSERT statement has been executed.

    IDENTITY - INSERT ステートメントが実行された後、Doctrine で利用可能な自動インクリメント ID などの IDENTIFY 戦略の使用。

  • SEQUENCE - Use of a database sequence to retrieve the entity-ids. This is possible before the INSERT statement is executed.

    SEQUENCE - エンティティ ID を取得するためのデータベース シーケンスの使用。これは、INSERT ステートメントが実行される前に可能です。

If you are using the SEQUENCE strategy you can define an additional element to describe the sequence:

SEQUENCE 戦略を使用している場合は、シーケンスを記述する追加の要素を定義できます。

<entity name="MyProject\User">
    <id name="id" type="integer" column="user_id">
        <generator strategy="SEQUENCE" />
        <sequence-generator sequence-name="user_seq" allocation-size="5" initial-value="1" />
    </id>
</entity>

Required attributes for <sequence-generator />:

の必須属性:

  • sequence-name - The name of the sequence

    sequence-name - シーケンスの名前

Optional attributes for <sequence-generator />:

のオプション属性:

  • allocation-size - By how much steps should the sequence be incremented when a value is retrieved. Defaults to 1

    割り当てサイズ - 値を取得するときにシーケンスをインクリメントするステップ数。デフォルトは 1

  • initial-value - What should the initial value of the sequence be.

    initial-value - シーケンスの初期値。

    NOTE

    ノート

    If you want to implement a cross-vendor compatible application you have to specify and additionally define the <sequence-generator /> element, if Doctrine chooses the sequence strategy for a platform.

    ベンダー間で互換性のあるアプリケーションを実装したい場合、Doctrine がプラットフォームのシーケンス戦略を選択する場合、要素を指定して追加で定義する必要があります。

21.5. Defining a Mapped Superclass

Sometimes you want to define a class that multiple entities inherit from, which itself is not an entity however. The chapter on Inheritance Mapping describes a Mapped Superclass in detail. You can define it in XML using the <mapped-superclass /> tag.

複数のエンティティが継承するクラスを定義したい場合がありますが、それ自体はエンティティではありません。継承マッピングの章では、マップされたスーパークラスについて詳しく説明しています。タグを使用して XML で定義できます。

<doctrine-mapping>
    <mapped-superclass name="MyProject\BaseClass">
        <field name="created" type="datetime" />
        <field name="updated" type="datetime" />
    </mapped-superclass>
</doctrine-mapping>

Required attributes:

必須属性:

  • name - Class name of the mapped superclass.

    name - マップされたスーパークラスのクラス名。

You can nest any number of <field /> and unidirectional <many-to-one /> or <one-to-one /> associations inside a mapped superclass.

マップされたスーパークラス内に任意の数の単方向または関連付けをネストできます。

21.6. Defining Inheritance Mappings

There are currently two inheritance persistence strategies that you can choose from when defining entities that inherit from each other. Single Table inheritance saves the fields of the complete inheritance hierarchy in a single table, joined table inheritance creates a table for each entity combining the fields using join conditions.

現在、相互に継承するエンティティを定義するときに選択できる継承永続化戦略は 2 つあります。単一テーブル継承は、完全な継承階層のフィールドを単一テーブルに保存します。結合テーブル継承は、結合条件を使用してフィールドを結合するエンティティごとにテーブルを作成します。

You can specify the inheritance type in the <entity /> element and then use the <discriminator-column /> and <discriminator-mapping /> attributes.

要素で継承タイプを指定し、and 属性を使用できます。

<entity name="MyProject\Animal" inheritance-type="JOINED">
    <discriminator-column name="discr" type="string" />
    <discriminator-map>
        <discriminator-mapping value="cat" class="MyProject\Cat" />
        <discriminator-mapping value="dog" class="MyProject\Dog" />
        <discriminator-mapping value="mouse" class="MyProject\Mouse" />
    </discriminator-map>
</entity>

The allowed values for inheritance-type attribute are JOINED or SINGLE_TABLE.

inheritance-type 属性に使用できる値は、JOINED または SINGLE_TABLE です。

Note

ノート

All inheritance related definitions have to be defined on the root entity of the hierarchy.

すべての継承関連の定義は、階層の rootentity で定義する必要があります。

21.7. Defining Lifecycle Callbacks

You can define the lifecycle callback methods on your entities using the <lifecycle-callbacks /> element:

要素を使用して、エンティティにライフサイクル コールバック メソッドを定義できます。

<entity name="Doctrine\Tests\ORM\Mapping\User" table="cms_users">

    <lifecycle-callbacks>
        <lifecycle-callback type="prePersist" method="onPrePersist" />
    </lifecycle-callbacks>
</entity>

21.8. Defining One-To-One Relations

You can define One-To-One Relations/Associations using the <one-to-one /> element. The required and optional attributes depend on the associations being on the inverse or owning side.

要素を使用して、1 対 1 の関係/関連付けを定義できます。必須およびオプションの属性は、逆側または所有側にある関連付けによって異なります。

For the inverse side the mapping is as simple as:

逆側の場合、マッピングは次のように単純です。

<entity class="MyProject\User">
    <one-to-one field="address" target-entity="Address" mapped-by="user" />
</entity>

Required attributes for inverse One-To-One:

逆 One-To-One の必須属性:

  • field - Name of the property/field on the entity’s PHP class.

    field - エンティティの PHP クラスのプロパティ/フィールドの名前。

  • target-entity - Name of the entity associated entity class. If this is not qualified the namespace of the current class is prepended. IMPORTANT: No leading backslash!

    target-entity - エンティティに関連付けられたエンティティ クラスの名前。これが修飾されていない場合、現在のクラスの名前空間が先頭に追加されます。重要: 先頭にバックスラッシュはありません!

  • mapped-by - Name of the field on the owning side (here Address entity) that contains the owning side association.

    maps-by - 所有側の関連付けを含む所有側 (ここでは Addressentity) のフィールドの名前。

For the owning side this mapping would look like:

所有側の場合、このマッピングは次のようになります。

<entity class="MyProject\Address">
    <one-to-one field="user" target-entity="User" inversed-by="address" />
</entity>

Required attributes for owning One-to-One:

One-to-One を所有するための必須属性:

  • field - Name of the property/field on the entity’s PHP class.

    field - エンティティの PHP クラスのプロパティ/フィールドの名前。

  • target-entity - Name of the entity associated entity class. If this is not qualified the namespace of the current class is prepended. IMPORTANT: No leading backslash!

    target-entity - エンティティに関連付けられたエンティティ クラスの名前。これが修飾されていない場合、現在のクラスの名前空間が先頭に追加されます。重要: 先頭にバックスラッシュはありません!

Optional attributes for owning One-to-One:

One-to-One を所有するためのオプションの属性:

  • inversed-by - If the association is bidirectional the inversed-by attribute has to be specified with the name of the field on the inverse entity that contains the back-reference.

    inversed-by - アソシエーションが双方向の場合、逆参照を含む逆エンティティのフィールドの名前で inversed-by 属性を指定する必要があります。

  • orphan-removal - If true, the inverse side entity is always deleted when the owning side entity is. Defaults to false.

    orphan-removal - true の場合、所有側エンティティが削除されると、逆側エンティティは常に削除されます。デフォルトは false です。

  • fetch - Either LAZY or EAGER, defaults to LAZY. This attribute makes only sense on the owning side, the inverse side ALWAYS has to use the FETCH strategy.

    fetch - LAZY または EAGER のいずれかで、デフォルトは LAZY です。この属性は、所有側でのみ意味を持ち、逆側では常に FETCH 戦略を使用する必要があります。

The definition for the owning side relies on a bunch of mapping defaults for the join column names. Without the nested <join-column /> element Doctrine assumes to foreign key to be called user_id on the Address Entities table. This is because the MyProject\Address entity is the owning side of this association, which means it contains the foreign key.

所有側の定義は、結合列名の一連のマッピングデフォルトに依存しています。ネストされた要素がない場合、Doctrine は Address Entities テーブルの user_id と呼ばれる外部キーを想定します。これは、MyProject\Address エンティティがこの関連付けの所有側であり、外部キーが含まれているためです。

The completed explicitly defined mapping is:

完成した明示的に定義されたマッピングは次のとおりです。

<entity class="MyProject\Address">
    <one-to-one field="user" target-entity="User" inversed-by="address">
        <join-column name="user_id" referenced-column-name="id" />
    </one-to-one>
</entity>

21.9. Defining Many-To-One Associations

The many-to-one association is ALWAYS the owning side of any bidirectional association. This simplifies the mapping compared to the one-to-one case. The minimal mapping for this association looks like:

多対一の関連付けは、常に双方向の関連付けの所有側です。これにより、1 対 1 の場合に比べてマッピングが簡素化されます。この関連付けの最小限のマッピングは次のようになります。

<entity class="MyProject\Article">
    <many-to-one field="author" target-entity="User" />
</entity>

Required attributes:

必須属性:

  • field - Name of the property/field on the entity’s PHP class.

    field - エンティティの PHP クラスのプロパティ/フィールドの名前。

  • target-entity - Name of the entity associated entity class. If this is not qualified the namespace of the current class is prepended. IMPORTANT: No leading backslash!

    target-entity - エンティティに関連付けられたエンティティ クラスの名前。これが修飾されていない場合、現在のクラスの名前空間が先頭に追加されます。重要: 先頭にバックスラッシュはありません!

Optional attributes:

オプションの属性:

  • inversed-by - If the association is bidirectional the inversed-by attribute has to be specified with the name of the field on the inverse entity that contains the back-reference.

    inversed-by - アソシエーションが双方向の場合、逆参照を含む逆エンティティのフィールドの名前で inversed-by 属性を指定する必要があります。

  • orphan-removal - If true the entity on the inverse side is always deleted when the owning side entity is and it is not connected to any other owning side entity anymore. Defaults to false.

    orphan-removal - true の場合、所有側エンティティが他の所有側エンティティに接続されていない場合、反対側のエンティティは常に削除されます。デフォルトは false です。

  • fetch - Either LAZY or EAGER, defaults to LAZY.

    fetch - LAZY または EAGER のいずれかで、デフォルトは LAZY です。

This definition relies on a bunch of mapping defaults with regards to the naming of the join-column/foreign key. The explicitly defined mapping includes a <join-column /> tag nested inside the many-to-one association tag:

この定義は、結合列/外部キーの命名に関して一連のマッピングのデフォルトに依存しています。明示的に定義されたマッピングには、多対 1 関連タグ内にネストされたタグが含まれます。

<entity class="MyProject\Article">
    <many-to-one field="author" target-entity="User">
        <join-column name="author_id" referenced-column-name="id" />
    </many-to-one>
</entity>

The join-column attribute name specifies the column name of the foreign key and the referenced-column-name attribute specifies the name of the primary key column on the User entity.

join-column 属性 name は外部キーの列名を指定し、 referenced-column-name 属性は User エンティティの主キー列の名前を指定します。

21.10. Defining One-To-Many Associations

The one-to-many association is ALWAYS the inverse side of any association. There exists no such thing as a uni-directional one-to-many association, which means this association only ever exists for bi-directional associations.

1 対多の関連付けは、常に任意の関連付けの逆側です。単方向の 1 対多の関連付けなどは存在しません。つまり、この関連付けは双方向の関連付けに対してのみ存在します。

<entity class="MyProject\User">
    <one-to-many field="phonenumbers" target-entity="Phonenumber" mapped-by="user" />
</entity>

Required attributes:

必須属性:

  • field - Name of the property/field on the entity’s PHP class.

    field - エンティティの PHP クラスのプロパティ/フィールドの名前。

  • target-entity - Name of the entity associated entity class. If this is not qualified the namespace of the current class is prepended. IMPORTANT: No leading backslash!

    target-entity - エンティティに関連付けられたエンティティ クラスの名前。これが修飾されていない場合、現在のクラスの名前空間が先頭に追加されます。重要: 先頭にバックスラッシュはありません!

  • mapped-by - Name of the field on the owning side (here Phonenumber entity) that contains the owning side association.

    mapping-by - 所有側の関連付けを含む所有側 (herePhonenumber エンティティ) のフィールドの名前。

Optional attributes:

オプションの属性:

  • fetch - Either LAZY, EXTRA_LAZY or EAGER, defaults to LAZY.

    fetch - LAZY、EXTRA_LAZY、または EAGER のいずれかで、デフォルトは LAZY です。

  • index-by: Index the collection by a field on the target entity.

    index-by: ターゲット エンティティのフィールドによってコレクションにインデックスを付けます。

21.11. Defining Many-To-Many Associations

From all the associations the many-to-many has the most complex definition. When you rely on the mapping defaults you can omit many definitions and rely on their implicit values.

すべての関連付けの中で、多対多の定義が最も複雑です。マッピングのデフォルトに依存する場合、多くの定義を省略して、それらの暗黙の値に依存できます。

<entity class="MyProject\User">
    <many-to-many field="groups" target-entity="Group" />
</entity>

Required attributes:

必須属性:

  • field - Name of the property/field on the entity’s PHP class.

    field - エンティティの PHP クラスのプロパティ/フィールドの名前。

  • target-entity - Name of the entity associated entity class. If this is not qualified the namespace of the current class is prepended. IMPORTANT: No leading backslash!

    target-entity - エンティティに関連付けられたエンティティ クラスの名前。これが修飾されていない場合、現在のクラスの名前空間が先頭に追加されます。重要: 先頭にバックスラッシュはありません!

Optional attributes:

オプションの属性:

  • mapped-by - Name of the field on the owning side that contains the owning side association if the defined many-to-many association is on the inverse side.

    mapping-by - 定義された多対多の関連付けが逆側にある場合、所有側の関連付けを含む所有側のフィールドの名前。

  • inversed-by - If the association is bidirectional the inversed-by attribute has to be specified with the name of the field on the inverse entity that contains the back-reference.

    inversed-by - アソシエーションが双方向の場合、逆参照を含む逆エンティティのフィールドの名前で inversed-by 属性を指定する必要があります。

  • fetch - Either LAZY, EXTRA_LAZY or EAGER, defaults to LAZY.

    fetch - LAZY、EXTRA_LAZY、または EAGER のいずれかで、デフォルトは LAZY です。

  • index-by: Index the collection by a field on the target entity.

    index-by: ターゲット エンティティのフィールドによってコレクションにインデックスを付けます。

The mapping defaults would lead to a join-table with the name “User_Group” being created that contains two columns “user_id” and “group_id”. The explicit definition of this mapping would be:

マッピングのデフォルトにより、「user_id」と「group_id」の 2 つの列を含む「User_Group」という名前の結合テーブルが作成されます。このマッピングの明示的な定義は次のようになります。

<entity class="MyProject\User">
    <many-to-many field="groups" target-entity="Group">
        <join-table name="cms_users_groups">
            <join-columns>
                <join-column name="user_id" referenced-column-name="id"/>
            </join-columns>
            <inverse-join-columns>
                <join-column name="group_id" referenced-column-name="id"/>
            </inverse-join-columns>
        </join-table>
    </many-to-many>
</entity>

Here both the <join-columns> and <inverse-join-columns> tags are necessary to tell Doctrine for which side the specified join-columns apply. These are nested inside a <join-table /> attribute which allows to specify the table name of the many-to-many join-table.

ここでは、指定された結合列がどちらの側に適用されるかを Doctrine に伝えるために、 and タグの両方が必要です。これらは、多対多結合テーブルのテーブル名を指定できる属性内にネストされています。

21.12. Cascade Element

Doctrine allows cascading of several UnitOfWork operations to related entities. You can specify the cascade operations in the <cascade /> element inside any of the association mapping tags.

Doctrine では、複数の UnitOfWork 操作を関連するエンティティにカスケードできます。関連マッピングタグ内の要素でカスケード操作を指定できます。

<entity class="MyProject\User">
    <many-to-many field="groups" target-entity="Group">
        <cascade>
            <cascade-all/>
        </cascade>
    </many-to-many>
</entity>

Besides <cascade-all /> the following operations can be specified by their respective tags:

また、次の操作をそれぞれのタグで指定できます。

  • <cascade-persist />

  • <cascade-merge />

  • <cascade-remove />

  • <cascade-refresh />

  • <cascade-detach />

21.13. Join Column Element

In any explicitly defined association mapping you will need the <join-column /> tag. It defines how the foreign key and primary key names are called that are used for joining two entities.

明示的に定義されたアソシエーション マッピングでは、タグが必要になります。 2 つのエンティティを結合するために使用される外部キーと主キーの名前を呼び出す方法を定義します。

Required attributes:

必須属性:

  • name - The column name of the foreign key.

    name - 外部キーの列名。

  • referenced-column-name - The column name of the associated entities primary key

    referenced-column-name - associatedentities 主キーの列名

Optional attributes:

オプションの属性:

  • unique - If the join column should contain a UNIQUE constraint. This makes sense for Many-To-Many join-columns only to simulate a one-to-many unidirectional using a join-table.

    unique - 結合列に UNIQUE 制約を含める必要がある場合。これは、結合テーブルを使用して 1 対多の一方向をシミュレートするためにのみ、多対多の結合列に意味があります。

  • nullable - should the join column be nullable, defaults to true.

    nullable - 結合列が null 可能である必要があります。デフォルトは true です。

  • on-delete - Foreign Key Cascade action to perform when entity is deleted, defaults to NO ACTION/RESTRICT but can be set to “CASCADE”.

    on-delete - エンティティが削除されたときに実行する外部キー カスケード アクション。デフォルトは NO ACTION/RESTRICT ですが、「CASCADE」に設定できます。

21.14. Defining Order of To-Many Associations

You can require one-to-many or many-to-many associations to be retrieved using an additional ORDER BY.

追加の ORDER BY を使用して、1 対多または多対多の関連付けを取得するように要求できます。

<entity class="MyProject\User">
    <many-to-many field="groups" target-entity="Group">
        <order-by>
            <order-by-field name="name" direction="ASC" />
        </order-by>
    </many-to-many>
</entity>

21.15. Defining Indexes or Unique Constraints

To define additional indexes or unique constraints on the entities table you can use the <indexes /> and <unique-constraints /> elements:

entitytable に追加のインデックスまたは一意の制約を定義するには、 and 要素を使用できます。

<entity name="Doctrine\Tests\ORM\Mapping\User" table="cms_users">

    <indexes>
        <index name="name_idx" columns="name"/>
        <index columns="user_email"/>
    </indexes>

    <unique-constraints>
        <unique-constraint columns="name,user_email" name="search_idx" />
    </unique-constraints>
</entity>

You have to specify the column and not the entity-class field names in the index and unique-constraint definitions.

インデックスと一意の制約の定義では、エンティティ クラスのフィールド名ではなく、列を指定する必要があります。

21.16. Derived Entities ID syntax

If the primary key of an entity contains a foreign key to another entity we speak of a derived entity relationship. You can define this in XML with the “association-key” attribute in the <id> tag.

エンティティの主キーに別のエンティティへの外部キーが含まれている場合、派生エンティティ関係について説明します。これは、タグの「関連付けキー」属性を使用して XML で定義できます。

<doctrine-mapping xmlns="https://doctrine-project.org/schemas/orm/doctrine-mapping"
      xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="https://doctrine-project.org/schemas/orm/doctrine-mapping
                          https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd">

     <entity name="Application\Model\ArticleAttribute">
        <id name="article" association-key="true" />
        <id name="attribute" type="string" />

        <field name="value" type="string" />

        <many-to-one field="article" target-entity="Article" inversed-by="attributes" />
     </entity>

</doctrine-mapping>

Table Of Contents

Previous topic

20. Attributes Reference

20. 属性リファレンス

Next topic

22. YAML Mapping

22. YAML マッピング

This Page

Fork me on GitHub