Override Field Association Mappings In Subclasses

Sometimes there is a need to persist entities but override all or part of the mapping metadata. Sometimes also the mapping to override comes from entities using traits where the traits have mapping metadata. This tutorial explains how to override mapping metadata, i.e. attributes and associations metadata in particular. The example here shows the overriding of a class that uses a trait but is similar when extending a base class as shown at the end of this tutorial.

エンティティを永続化する必要があるが、マッピング メタデータのすべてまたは一部をオーバーライドする必要がある場合があります。オーバーライドするマッピングは、特性がマッピング メタデータを持つ特性を使用するエンティティから取得されることもあります。このチュートリアルでは、マッピング メタデータをオーバーライドする方法について説明します。特に属性と関連付けのメタデータ。ここの例は、特性を使用するクラスのオーバーライドを示していますが、このチュートリアルの最後に示されているように、基本クラスを拡張する場合も同様です。

Suppose we have a class ExampleEntityWithOverride. This class uses trait ExampleTrait:

クラス ExampleEntityWithOverride があるとします。このクラスは特性 ExampleTrait を使用します:

<?php

#[Entity]
#[AttributeOverrides([
    new AttributeOverride('foo', [
        'column' => new Column([
            'name' => 'foo_overridden',
            'type' => 'integer',
            'length' => 140,
            'nullable' => false,
            'unique' => false,
        ]),
    ]),
])]
#[AssociationOverrides([
    new AssociationOverride('bar', [
        'joinColumns' => new JoinColumn([
            'name' => 'example_entity_overridden_bar_id',
            'referencedColumnName' => 'id',
        ]),
    ]),
])]
class ExampleEntityWithOverride
{
    use ExampleTrait;
}

#[Entity]
class Bar
{
    #[Id, Column(type: 'string')]
    private $id;
}

The docblock is showing metadata override of the attribute and association type. It basically changes the names of the columns mapped for a property foo and for the association bar which relates to Bar class shown above. Here is the trait which has mapping metadata that is overridden by the attribute above:

docblock は、属性と関連付けタイプのメタデータ オーバーライドを示しています。基本的に、プロパティ foo および上記の Bar クラスに関連する関連バーにマップされた列の名前を変更します。上記の属性によってオーバーライドされるマッピング メタデータを持つ trait は次のとおりです。

<?php
/**
 * Trait class
 */
trait ExampleTrait
{
    #[Id, Column(type: 'integer')]
    private int|null $id = null;

    #[Column(name: 'trait_foo', type: 'integer', length: 100, nullable: true, unique: true)]
    protected int $foo;

    #[OneToOne(targetEntity: Bar::class, cascade: ['persist', 'merge'])]
    #[JoinColumn(name: 'example_trait_bar_id', referencedColumnName: 'id')]
    protected Bar|null $bar = null;
}

The case for just extending a class would be just the same but:

クラスを拡張するだけの場合もまったく同じですが、次のようになります。

<?php
class ExampleEntityWithOverride extends BaseEntityWithSomeMapping
{
    // ...
}

Overriding is also supported via XML and YAML (examples).

オーバーライドは、XML および YAML 経由でもサポートされています (例)。

Previous topic

Ordering To-Many Associations

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

Next topic

30. Pagination

30. ページネーション

This Page

Fork me on GitHub