20. Attributes Reference¶
PHP 8 adds native support for metadata with its “Attributes” feature. Doctrine ORM provides support for mapping metadata using PHP attributes as of version 2.9.
The attributes metadata support is closely modelled after the already existing annotation metadata supported since the first version 2.0.
20.1. Index¶
- #[AssociationOverride]
- #[属性オーバーライド]
- #[桁]
- #[キャッシュ]
- #[ChangeTrackingPolicy
- #[CustomIdGenerator]
- #[DiscriminatorColumn]
- #[DiscriminatorMap]
- #[埋め込み可能]
- #[埋め込み]
- #[実在物]
- #[生成値]
- #[HasLifecycleCallbacks]
- #[索引]
- #[ID]
- #[継承タイプ]
- #[結合列]
- #[結合テーブル]
- #[多対一]
- #[多対多]
- #[MappedSuperclass]
- #[ワンツーワン]
- #[OneToMany]
- #[並べ替え]
- #[ロード後]
- #[PostPersist]
- #[PostRemove]
- #[更新後]
- #[PrePersist]
- #[事前削除]
- #[更新前]
- #[シーケンスジェネレーター]
- #[テーブル]
- #[ユニーク制約]
- #[バージョン]
20.2. Reference¶
20.2.1. #[AssociationOverride]¶
In an inheritance hierarchy this attribute allows to override the
assocation mapping definitions of the parent mappings. It needs to be nested
within a #[AssociationOverrides]
on the class level.
Required parameters:
name: Name of the association mapping to overwrite.
name: 上書きする関連付けマッピングの名前。
Optional parameters:
joinColumns: A list of nested
#[JoinColumn]
declarations.joinColumns: ネストされた #[JoinColumn] 宣言のリスト。joinTable: A nested
#[JoinTable]
declaration in case of a many-to-many overwrite.joinTable: 多対多の上書きの場合のネストされた #[JoinTable] 宣言。inversedBy: The name of the inversedBy field on the target entity side.
inversedBy: ターゲット エンティティ側の inversedBy フィールドの名前。fetch: The fetch strategy, one of: EAGER, LAZY, EXTRA_LAZY.
fetch: フェッチ戦略で、EAGER、LAZY、EXTRA_LAZY のいずれかです。
Examples:
<?php
use Doctrine\ORM\Mapping\AssociationOverride;
use Doctrine\ORM\Mapping\AssociationOverrides;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
#[AssociationOverrides([
new AssociationOverride(
name: "groups",
joinTable: new JoinTable(
name: "ddc964_users_admingroups",
),
joinColumns: [new JoinColumn(name: "adminuser_id")],
inverseJoinColumns: [new JoinColumn(name: "admingroup_id")]
),
new AssociationOverride(
name: "address",
joinColumns: [new JoinColumn(name: "adminaddress_id", referencedColumnName: "id")]
)
])]
class DDC964Admin extends DDC964User
{
}
20.2.2. #[AttributeOverride]¶
In an inheritance hierarchy this attribute allows to override the
field mapping definitions of the parent mappings. It needs to be nested
within a #[AttributeOverrides]
on the class level.
Required parameters:
name: Name of the association mapping to overwrite.
name: 上書きする関連付けマッピングの名前。column: A nested
#[Column]
attribute with the overwritten field settings.column: フィールド設定が上書きされたネストされた #[Column] 属性。
Examples:
<?php
use Doctrine\ORM\Mapping\AttributeOverride;
use Doctrine\ORM\Mapping\AttributeOverrides;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
#[Entity]
#[AttributeOverrides([
new AttributeOverride(
name: "id",
column: new Column(name: "guest_id", type: "integer", length: 140)
),
new AttributeOverride(
name: "name",
column: new Column(name: "guest_name", nullable: false, unique: true, length: 240)
)]
)]
class DDC964Guest extends DDC964User
{
}
20.2.3. #[Column]¶
Marks an annotated instance variable as “persistent”. It has to be inside the instance variables PHP DocBlock comment. Any value hold inside this variable will be saved to and loaded from the database as part of the lifecycle of the instance variables entity-class.
Required parameters:
type: Name of the DBAL Type which does the conversion between PHP and Database representation.
type: PHP とデータベース表現の間の変換を行う DBAL タイプの名前。
Optional parameters:
name: By default the property name is used for the database column name also, however the
name
attribute allows you to determine the column name.name: デフォルトでは、プロパティ名はデータベースの列名にも使用されますが、name 属性を使用して列名を決定できます。length: Used by the
string
type to determine its maximum length in the database. Doctrine does not validate the length of a string value for you.length: データベース内での最大長を決定するために文字列型によって使用されます。 Doctrine は astring 値の長さを検証しません。precision: 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.
精度: 10 進数 (正確な数値) 列の精度 (10 進数列にのみ適用)。これは、値に対して格納される最大桁数です。scale: 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: 10 進数 (正確な数値) 列のスケール (10 進数列にのみ適用)。これは、小数点の右側の桁数を表し、precision より大きくしてはなりません。unique: Boolean value to determine if the value of the column should be unique across all rows of the underlying entities table.
unique: 列の値が基になるエンティティ テーブルのすべての行で一意である必要があるかどうかを決定するブール値。- nullable: Determines if NULL values allowed for this column.
If not specified, default value is
false
.指定しない場合、デフォルト値は false です。
insertable: Boolean value to determine if the column should be included when inserting a new row into the underlying entities table. If not specified, default value is true.
insertable: 基になるエンティティ テーブルに新しい行を挿入するときに列を含める必要があるかどうかを決定するブール値。指定されていない場合、既定値は true です。updatable: Boolean value to determine if the column should be included when updating the row of the underlying entities table. If not specified, default value is true.
更新可能: 基になるエンティティ テーブルの行を更新するときに列を含める必要があるかどうかを決定するブール値。指定されていない場合、既定値は true です。generated: An enum with the possible values ALWAYS, INSERT, NEVER. Is used after an INSERT or UPDATE statement to determine if the database generated this value and it needs to be fetched using a SELECT statement.
generated: ALWAYS、INSERT、NEVER の可能な値を持つ列挙型。INSERT または UPDATE ステートメントの後に使用され、データベースがこの値を生成し、SELECT ステートメントを使用してフェッチする必要があるかどうかを判断します。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: スキーマ内の列のコメント (すべてのベンダーでサポートされているわけではありません)。charset
: The charset of the column (only supported by Mysql, PostgreSQL, Sqlite and SQLServer).charset: 列の文字セット (Mysql、PostgreSQL、Sqlite、および SQLServer でのみサポートされています)。collation
: The collation of the column (only supported by Mysql, PostgreSQL, Sqlite and SQLServer).collation: 列の照合 (Mysql、PostgreSQL、Sqlite、および SQLServer でのみサポートされています)。check
: Adds a check constraint type to the column (might not be supported by all vendors).check: 列にチェック制約タイプを追加します (すべてのベンダーでサポートされているわけではありません)。
columnDefinition: DDL SQL snippet that starts after the column name and specifies the complete (non-portable!) column definition. This attribute allows to make use of advanced RMDBS features. However you should make careful use of this feature and the consequences.
SchemaTool
will not detect changes on the column correctly anymore if you usecolumnDefinition
.columnDefinition: 列名の後に開始し、完全な (移植不可!) 列定義を指定する DDL SQL スニペット。この属性により、高度な RMDBS 機能を利用できます。ただし、この機能とその結果を慎重に使用する必要があります。 columnDefinition を使用すると、SchemaTool は列の変更を正しく検出しなくなります。Additionally you should remember that the
type
attribute still handles the conversion between PHP and Database values. If you use this attribute on a column that is used for joins between tables you should also take a look at #[JoinColumn].さらに、type 属性は PHP とデータベース値の間の変換を引き続き処理することを覚えておく必要があります。テーブル間の結合に使用される列でこの属性を使用する場合は、#[JoinColumn] も確認する必要があります。
Note
For more detailed information on each attribute, please refer to
the DBAL Schema-Representation
documentation.
Examples:
<?php
use Doctrine\ORM\Mapping\Column;
#[Column(type: "string", length: 32, unique: true, nullable: false)]
protected $username;
#[Column(type: "string", columnDefinition: "CHAR(2) NOT NULL")]
protected $country;
#[Column(type: "decimal", precision: 2, scale: 1)]
protected $height;
#[Column(type: "string", length: 2, options: [
"fixed" => true,
"comment" => "Initial letters of first and last name"
])]
protected $initials;
#[Column(
type: "integer",
name: "login_count",
nullable: false,
options: ["unsigned" => true, "default" => 0]
)]
protected $loginCount;
// MySQL example: full_name char(41) GENERATED ALWAYS AS (concat(firstname,' ',lastname)),
#[Column(
type: "string",
name: "user_fullname",
insertable: false,
updatable: false
)]
protected $fullname;
20.2.4. #[Cache]¶
Add caching strategy to a root entity or a collection.
Optional parameters:
usage: One of
READ_ONLY
,READ_WRITE
orNONSTRICT_READ_WRITE
, By default this isREAD_ONLY
.使用法: READ_ONLY、READ_WRITE または NONSTRICT_READ_WRITE のいずれか。デフォルトでは、これは READ_ONLY です。region: An specific region name
region: 特定の地域名
20.2.5. #[ChangeTrackingPolicy]¶
The Change Tracking Policy attribute allows to specify how the
Doctrine ORM UnitOfWork
should detect changes in properties of
entities during flush. By default each entity is checked according
to a deferred implicit strategy, which means upon flush UnitOfWork
compares all the properties of an entity to a previously stored
snapshot. This works out of the box, however you might want to
tweak the flush performance where using another change tracking
policy is an interesting option.
The details on all the available change tracking policies can be found in the configuration section.
Example:
<?php
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\ChangeTrackingPolicy;
#[
Entity,
ChangeTrackingPolicy("DEFERRED_IMPLICIT"),
ChangeTrackingPolicy("DEFERRED_EXPLICIT"),
ChangeTrackingPolicy("NOTIFY")
]
class User {}
20.2.6. #[CustomIdGenerator]¶
This attribute allows you to specify a user-provided class to generate identifiers. This attribute only works when both #[Id] and #[GeneratedValue(strategy: “CUSTOM”)] are specified.
Required parameters:
class: name of the class which should extend DoctrineORMIdAbstractIdGenerator
class: DoctrineORMIdAbstractIdGenerator を拡張するクラスの名前
Example:
<?php
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\CustomIdGenerator;
use App\Doctrine\MyIdGenerator;
#[Id]
#[Column(type: "integer")]
#[GeneratedValue(strategy: "CUSTOM")]
#[CustomIdGenerator(class: MyIdGenerator::class)]
public $id;
20.2.7. #[DiscriminatorColumn]¶
This attribute is optional and set on the root entity class of an inheritance hierarchy. It specifies the details of the column which saves the name of the class, which the entity is actually instantiated as.
If this attribute is not specified, the discriminator column defaults
to a string column of length 255 called dtype
.
Required parameters:
name: The column name of the discriminator. This name is also used during Array hydration as key to specify the class-name.
name: 識別子の列名。この名前は、クラス名を指定するキーとして配列ハイドレーション中にも使用されます。
Optional parameters:
type: By default this is string.
type: デフォルトでは、これは文字列です。length: By default this is 255.
長さ: デフォルトでは、これは 255 です。columnDefinition: By default this is null the definition according to the type will be used. This option allows to override it.
columnDefinition: デフォルトでは、これは null であり、タイプに応じた定義が使用されます。このオプションを使用すると、それをオーバーライドできます。enumType: By default this is null. Allows to map discriminatorColumn value to PHP enum
enumType: デフォルトでは、これは null です。 discriminatorColumn 値を PHP 列挙型にマップできるようにします
20.2.8. #[DiscriminatorMap]¶
The discriminator map is a required attribute on the root entity class in an inheritance hierarchy. Its only argument is an array which defines which class should be saved under which name in the database. Keys are the database value and values are the classes, either as fully- or as unqualified class names depending on whether the classes are in the namespace or not.
<?php
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\InheritanceType;
use Doctrine\ORM\Mapping\DiscriminatorColumn;
use Doctrine\ORM\Mapping\DiscriminatorMap;
#[Entity]
#[InheritanceType("JOINED")]
#[DiscriminatorColumn(name: "discr", type: "string")]
#[DiscriminatorMap(["person" => Person::class, "employee" => Employee::class])]
class Person
{
// ...
}
20.2.9. #[Embeddable]¶
The embeddable attribute is required on a class, in order to make it embeddable inside an entity. It works together with the #[Embedded] attribute to establish the relationship between the two classes.
<?php
use Doctrine\ORM\Mapping\Embeddable;
use Doctrine\ORM\Mapping\Embedded;
#[Embeddable]
class Address
{ /* .. */ }
class User
{
#[Embedded(class: Address::class)]
private $address;
20.2.10. #[Embedded]¶
The embedded attribute is required on an entity’s member variable, in order to specify that it is an embedded class.
Required parameters:
class: The embeddable class
class: 埋め込み可能なクラス
20.2.11. #[Entity]¶
Required attribute to mark a PHP class as an entity. Doctrine manages the persistence of all classes marked as entities.
Optional parameters:
repositoryClass: Specifies the FQCN of a subclass of the
EntityRepository
. Use of repositories for entities is encouraged to keep specialized DQL and SQL operations separated from the Model/Domain Layer.repositoryClass: theEntityRepository のサブクラスの FQCN を指定します。エンティティにリポジトリを使用して、特殊な DQL および SQL 操作を Model/DomainLayer から分離しておくことをお勧めします。readOnly: 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.
readOnly: このエンティティが読み取り専用としてマークされ、変更の追跡が考慮されないことを指定します。ただし、このタイプのエンティティは永続化および削除できます。
Example:
<?php
use Doctrine\ORM\Mapping\Entity;
use MyProject\Repository\UserRepository;
#[Entity(repositoryClass: UserRepository::class, readOnly: false)]
class User
{
// ...
}
20.2.12. #[GeneratedValue]¶
Specifies which strategy is used for identifier generation for an instance variable which is annotated by #[Id]. This attribute is optional and only has meaning when used in conjunction with #[Id].
If this attribute is not specified with #[Id]
the NONE
strategy is
used as default.
Optional parameters:
strategy: Set the name of the identifier generation strategy. Valid values are
AUTO
,SEQUENCE
,IDENTITY
,UUID
(deprecated),CUSTOM
andNONE
. If not specified, the default value isAUTO
.戦略: 識別子生成戦略の名前を設定します。有効な値は、AUTO、SEQUENCE、IDENTITY、UUID (非推奨)、CUSTOM、および NONE です。指定されていない場合、デフォルト値は AUTO です。
Example:
<?php
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Id;
#[Id, Column(type: "integer"), GeneratedValue(strategy: "IDENTITY")]
protected $id = null;
20.2.13. #[HasLifecycleCallbacks]¶
This attribute has to be set on the entity-class to
notify Doctrine that this entity has entity lifecycle callback
attributes set on at least one of its methods. Using #[PostLoad],
#[PrePersist]
, #[PostPersist]
, #[PreRemove]
, #[PostRemove]
,
#[PreUpdate]
or #[PostUpdate]
without this marker attribute will
make Doctrine ignore the callbacks.
Example:
<?php
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\HasLifecycleCallbacks;
use Doctrine\ORM\Mapping\PostPersist;
#[Entity, HasLifecycleCallbacks]
class User
{
#[PostPersist]
public function sendOptinMail() {}
}
20.2.14. #[Index]¶
Attribute is used on the entity-class level. It provides a hint to the SchemaTool to
generate a database index on the specified table columns. It only
has meaning in the SchemaTool
schema generation context.
Required parameters:
name: Name of the Index
name: インデックスの名前fields: Array of fields. Exactly one of fields, columns is required.
fields: フィールドの配列。フィールド、列の 1 つだけが必要です。columns: Array of columns. Exactly one of fields, columns is required.
列: 列の配列。フィールド、列の 1 つだけが必要です。
Optional parameters:
options: Array of platform specific options:
options: プラットフォーム固有のオプションの配列:where
: SQL WHERE condition to be used for partial indexes. It will only have effect on supported platforms.where: 部分インデックスに使用する SQL WHERE 条件。サポートされているプラットフォームでのみ効果があります。
Basic example:
<?php
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Index;
#[Entity]
#[Index(name: "category_idx", columns: ["category"])]
#[Index(name: "brand_idx", fields: ["brand"])]
class ECommerceProduct
{
}
Example with partial indexes:
<?php
use Doctrine\ORM\Mapping\Index;
#[Index(name: "search_idx", columns: ["category"],
options: [
"where": "((category IS NOT NULL))"
]
)]
class ECommerceProduct
{
}
20.2.15. #[Id]¶
The annotated instance variable will be marked as entity
identifier, the primary key in the database. This attribute is a
marker only and has no required or optional attributes. For
entities that have multiple identifier columns each column has to
be marked with #[Id]
.
Example:
<?php
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Id;
#[Id, Column(type: "integer")]
protected $id = null;
20.2.16. #[InheritanceType]¶
In an inheritance hierarchy you have to use this attribute on the topmost/super class to define which strategy should be used for inheritance. Currently Single Table and Class Table Inheritance are supported.
This attribute has always been used in conjunction with the #[DiscriminatorMap] and #[DiscriminatorColumn] attributes.
Examples:
<?php
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\InheritanceType;
use Doctrine\ORM\Mapping\DiscriminatorColumn;
use Doctrine\ORM\Mapping\DiscriminatorMap;
#[Entity]
#[InheritanceType("SINGLE_TABLE")]
#[DiscriminatorColumn(name: "discr", type: "string")]
#[DiscriminatorMap(["person" => "Person", "employee" => "Employee"])]
class Person
{
// ...
}
#[Entity]
#[InheritanceType("JOINED")]
#[DiscriminatorColumn(name: "discr", type: "string")]
#[DiscriminatorMap(["person" => "Person", "employee" => "Employee"])]
class Person
{
// ...
}
20.2.17. #[JoinColumn], #[InverseJoinColumn]¶
This attribute is used in the context of relations in #[ManyToOne], #[OneToOne] fields and in the Context of a #[ManyToMany]. If this attribute or both name and referencedColumnName are missing they will be computed considering the field’s name and the current naming strategy.
The #[InverseJoinColumn]
is the same as #[JoinColumn]
and is used in the context
of a #[ManyToMany]
attribute declaration to specifiy the details of the join table’s
column information used for the join to the inverse entity. This is only required
on PHP 8.0, where nested attributes are not yet supported.
Optional parameters:
name: Column name that holds the foreign key identifier for this relation. In the context of
#[JoinTable]
it specifies the column name in the join table.name: この関係の外部キー識別子を保持する列名。 #[JoinTable] のコンテキストでは、結合テーブルの列名を指定します。referencedColumnName: Name of the primary key identifier that is used for joining of this relation. Defaults to
id
.referencedColumnName: この関係の結合に使用される主キー識別子の名前。デフォルトは ID です。unique: Determines whether this relation is exclusive between the affected entities and should be enforced as such on the database constraint level. Defaults to false.
unique: この関係が、影響を受けるエンティティ間で排他的であり、データベース制約レベルでそのように強制する必要があるかどうかを決定します。デフォルトは false です。nullable: Determine whether the related entity is required, or if null is an allowed state for the relation. Defaults to true.
nullable: 関連するエンティティが必須かどうか、または null の場合は関係の許可された状態かどうかを決定します。デフォルトは true です。onDelete: Cascade Action (Database-level)
onDelete: カスケード アクション (データベース レベル)columnDefinition: DDL SQL snippet that starts after the column name and specifies the complete (non-portable!) column definition. This attribute enables the use of advanced RMDBS features. Using this attribute on
#[JoinColumn]
is necessary if you need slightly different column definitions for joining columns, for example regarding NULL/NOT NULL defaults. However by default a “columnDefinition” attribute on #[Column] also sets the related#[JoinColumn]
’s columnDefinition. This is necessary to make foreign keys work.columnDefinition: columnname の後に開始し、完全な (移植不可!) 列定義を指定する DDL SQL スニペット。この属性により、高度な RMDBS 機能を使用できるようになります。 #[JoinColumn] でこの属性を使用する必要があるのは、たとえば NULL/NOT NULL のデフォルトに関して、列を結合するためにわずかに異なる列定義が必要な場合です。ただし、デフォルトでは、#[Column] の「columnDefinition」属性は、関連する #[JoinColumn] の columnDefinition も設定します。これは、外部キーを機能させるために必要です。options: See “options” attribute on #[Column].
options: #[Column] の「options」属性を参照してください。
Example:
<?php
use Doctrine\ORM\Mapping\OneToOne;
use Doctrine\ORM\Mapping\JoinColumn;
#[OneToOne(targetEntity: Customer::class)]
#[JoinColumn(name: "customer_id", referencedColumnName: "id")]
private $customer;
20.2.18. #[JoinTable]¶
Using
#[ManytoMany] on the owning side of the relation
requires to specify the #[JoinTable] attribute which describes the
details of the database join table. If you do not specify
#[JoinTable]
on these relations reasonable mapping defaults apply
using the affected table and the column names.
A notable difference to the annotation metadata support, #[JoinColumn]
and #[InverseJoinColumn]
can be specified at the property level and are not
nested within the #[JoinTable]
attribute.
Required attribute:
name: Database name of the join-table
name: 結合テーブルのデータベース名
Example:
<?php
use Doctrine\ORM\Mapping\ManyToMany;
use Doctrine\ORM\Mapping\JoinTable;
#[ManyToMany(targetEntity: "Phonenumber")]
#[JoinTable(name: "users_phonenumbers")]
public $phonenumbers;
20.2.19. #[ManyToOne]¶
Defines that the annotated instance variable holds a reference that describes a many-to-one relationship between two entities.
Required parameters:
targetEntity: FQCN of the referenced target entity. Can be the unqualified class name if both classes are in the same namespace. IMPORTANT: No leading backslash!
targetEntity: 参照されるターゲット エンティティの FQCN。両方のクラスが同じ名前空間にある場合は、非修飾クラス名にすることができます。重要: 先頭のバックスラッシュは使用しないでください。
Optional parameters:
cascade: Cascade Option
cascade: カスケードオプションfetch: One of LAZY or EAGER
fetch: LAZY または EAGER のいずれかinversedBy - The inversedBy attribute designates the field in the entity that is the inverse side of the relationship.
inversedBy - inversedBy 属性は、関係の逆側であるエンティティ内のフィールドを指定します。
Example:
<?php
use Doctrine\ORM\Mapping\ManyToOne;
#[ManyToOne(targetEntity: "Cart", cascade: ["all"], fetch: "EAGER")]
private $cart;
20.2.20. #[ManyToMany]¶
Defines that the annotated instance variable holds a many-to-many relationship between two entities. #[JoinTable] is an additional, optional attribute that has reasonable default configuration values using the table and names of the two related entities.
Required parameters:
targetEntity: FQCN of the referenced target entity. Can be the unqualified class name if both classes are in the same namespace. IMPORTANT: No leading backslash!
targetEntity: 参照されるターゲット エンティティの FQCN。両方のクラスが同じ名前空間にある場合は、非修飾クラス名にすることができます。重要: 先頭のバックスラッシュは使用しないでください。
Optional parameters:
mappedBy: This option specifies the property name on the targetEntity that is the owning side of this relation. It is a required attribute for the inverse side of a relationship.
MappedBy: このオプションは、この関係の所有側である targetEntity のプロパティ名を指定します。リレーションシップの逆側の必須属性です。inversedBy: The inversedBy attribute designates the field in the entity that is the inverse side of the relationship.
inversedBy: inversedBy 属性は、関係の逆側であるエンティティ内のフィールドを指定します。cascade: Cascade Option
cascade: カスケードオプションfetch: One of
LAZY
,EXTRA_LAZY
orEAGER
fetch: LAZY、EXTRA_LAZY、または EAGER のいずれかindexBy: Index the collection by a field on the target entity.
indexBy: ターゲット エンティティのフィールドによってコレクションにインデックスを付けます。
Note
For ManyToMany
bidirectional relationships either side may
be the owning side (the side that defines the #[JoinTable]
and/or
does not make use of the mappedBy attribute, thus using a default
join table).
Example:
<?php
use Doctrine\ORM\Mapping\ManyToMany;
use Doctrine\ORM\Mapping\JoinColumn;
use Doctrine\ORM\Mapping\InverseJoinColumn;
use Doctrine\ORM\Mapping\JoinTable;
/** Owning Side */
#[ManyToMany(targetEntity: "Group", inversedBy: "features")]
#[JoinTable(name: "user_groups")]
#[JoinColumn(name: "user_id", referencedColumnName: "id")]
#[InverseJoinColumn(name: "group_id", referencedColumnName: "id")]
private $groups;
/** Inverse Side */
#[ManyToMany(targetEntity: "User", mappedBy: "groups")]
private $features;
20.2.21. #[MappedSuperclass]¶
A mapped superclass is an abstract or concrete class that provides persistent entity state and mapping information for its subclasses, but which is not itself an entity. This attribute is specified on the Class level and has no additional settings.
The #[MappedSuperclass]
attribute cannot be used in conjunction with
#[Entity]
. See the Inheritance Mapping section for
more details on the restrictions of mapped superclasses.
Optional parameters:
repositoryClass: Specifies the FQCN of a subclass of the EntityRepository. That will be inherited for all subclasses of that Mapped Superclass.
repositoryClass: EntityRepository のサブクラスの FQCN を指定します。これは、Mapped Superclass のすべてのサブクラスに継承されます。
Example:
<?php
use Doctrine\ORM\Mapping\MappedSuperclass;
use Doctrine\ORM\Mapping\Entity;
#[MappedSuperclass]
abstract class BaseEntity
{
// ... fields and methods
}
#[Entity]
class EntitySubClassFoo extends BaseEntity
{
// ... fields and methods
}
20.2.22. #[OneToOne]¶
The #[OneToOne]
attribute works almost exactly as the
#[ManyToOne] with one additional option which can
be specified. When no
#[JoinColumn] is specified it defaults to using the target entity table and
primary key column names and the current naming strategy to determine a name for the join column.
Required parameters:
targetEntity: FQCN of the referenced target entity. Can be the unqualified class name if both classes are in the same namespace. IMPORTANT: No leading backslash!
targetEntity: 参照されるターゲット エンティティの FQCN。両方のクラスが同じ名前空間にある場合は、非修飾クラス名にすることができます。重要: 先頭のバックスラッシュは使用しないでください。
Optional parameters:
cascade: Cascade Option
cascade: カスケードオプションfetch: One of LAZY or EAGER
fetch: LAZY または EAGER のいずれかorphanRemoval: Boolean that specifies if orphans, inverse OneToOne entities that are not connected to any owning instance, should be removed by Doctrine. Defaults to false.
orphanRemoval: どの所有インスタンスにも接続されていない孤立した inverseOneToOne エンティティを Doctrine によって削除する必要があるかどうかを指定するブール値。デフォルトは false です。inversedBy: The inversedBy attribute designates the field in the entity that is the inverse side of the relationship.
inversedBy: inversedBy 属性は、関係の逆側であるエンティティ内のフィールドを指定します。
Example:
<?php
#[OneToOne(targetEntity: "Customer")]
#[JoinColumn(name: "customer_id", referencedColumnName: "id")]
private $customer;
20.2.23. #[OneToMany]¶
Required parameters:
targetEntity: FQCN of the referenced target entity. Can be the unqualified class name if both classes are in the same namespace. IMPORTANT: No leading backslash!
targetEntity: 参照されるターゲット エンティティの FQCN。両方のクラスが同じ名前空間にある場合は、非修飾クラス名にすることができます。重要: 先頭のバックスラッシュは使用しないでください。
Optional parameters:
cascade: Cascade Option
cascade: カスケードオプションorphanRemoval: Boolean that specifies if orphans, inverse OneToOne entities that are not connected to any owning instance, should be removed by Doctrine. Defaults to false.
orphanRemoval: どの所有インスタンスにも接続されていない孤立した inverseOneToOne エンティティを Doctrine によって削除する必要があるかどうかを指定するブール値。デフォルトは false です。mappedBy: This option specifies the property name on the targetEntity that is the owning side of this relation. Its a required attribute for the inverse side of a relationship.
MappedBy: このオプションは、この関係の所有側である targetEntity のプロパティ名を指定します。リレーションシップの逆側に必要な属性です。fetch: One of LAZY, EXTRA_LAZY or EAGER.
fetch: LAZY、EXTRA_LAZY、または EAGER のいずれか。indexBy: Index the collection by a field on the target entity.
indexBy: ターゲット エンティティのフィールドによってコレクションにインデックスを付けます。
Example:
<?php
use Doctrine\ORM\Mapping\OneToMany;
#[OneToMany(
targetEntity: "Phonenumber",
mappedBy: "user",
cascade: ["persist", "remove", "merge"],
orphanRemoval: true)
]
public $phonenumbers;
20.2.24. #[OrderBy]¶
Optional attribute that can be specified with a #[ManyToMany] or #[OneToMany] attribute to specify by which criteria the collection should be retrieved from the database by using an ORDER BY clause.
Example:
<?php
#[ManyToMany(targetEntity: "Group")]
#[OrderBy(["name" => "ASC"])]
private $groups;
The key in OrderBy
is only allowed to consist of
unqualified, unquoted field names and of an optional ASC
/DESC
positional statement. Multiple Fields are separated by a comma (,).
The referenced field names have to exist on the targetEntity
class of the #[ManyToMany]
or #[OneToMany]
attribute.
20.2.25. #[PostLoad]¶
Marks a method on the entity to be called as a #[PostLoad]
event.
Only works with #[HasLifecycleCallbacks]
in the entity class PHP
level.
20.2.26. #[PostPersist]¶
Marks a method on the entity to be called as a #[PostPersist]
event.
Only works with #[HasLifecycleCallbacks]
in the entity class PHP
level.
20.2.27. #[PostRemove]¶
Marks a method on the entity to be called as a #[PostRemove]
event.
Only works with #[HasLifecycleCallbacks]
in the entity class PHP
level.
20.2.28. #[PostUpdate]¶
Marks a method on the entity to be called as a #[PostUpdate]
event.
Only works with #[HasLifecycleCallbacks]
in the entity class PHP
level.
20.2.29. #[PrePersist]¶
Marks a method on the entity to be called as a #[PrePersist]
event.
Only works with #[HasLifecycleCallbacks]
in the entity class PHP
level.
20.2.30. #[PreRemove]¶
Marks a method on the entity to be called as a #``[PreRemove]`` event.
Only works with #[HasLifecycleCallbacks]
in the entity class PHP
level.
20.2.31. #[PreUpdate]¶
Marks a method on the entity to be called as a #[PreUpdate]
event.
Only works with #[HasLifecycleCallbacks]
in the entity class PHP
level.
20.2.32. #[SequenceGenerator]¶
For use with #[GeneratedValue(strategy: "SEQUENCE")]
this
attribute allows to specify details about the sequence, such as
the increment size and initial values of the sequence.
Required parameters:
sequenceName: Name of the sequence
sequenceName: シーケンスの名前
Optional parameters:
allocationSize: Increment the sequence by the allocation size when its fetched. A value larger than 1 allows optimization for scenarios where you create more than one new entity per request. Defaults to 10
allocationSize: 取得時に割り当てサイズだけシーケンスをインクリメントします。 1 より大きい値を指定すると、リクエストごとに複数の新しいエンティティを作成するシナリオの最適化が可能になります。デフォルトは 10 です。initialValue: Where the sequence starts, defaults to 1.
initialValue: シーケンスが開始する場所。デフォルトは 1 です。
Example:
<?php
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\SequenceGenerator;
#[Id]
#[GeneratedValue(strategy: "SEQUENCE")]
#[Column(type: "integer")]
#[SequenceGenerator(sequenceName: "tablename_seq", initialValue: 1, allocationSize: 100)]
protected $id = null;
20.2.33. #[Table]¶
Attribute describes the table an entity is persisted in. It is placed on the entity-class level and is optional. If it is not specified the table name will default to the entity’s unqualified classname.
Required parameters:
name: Name of the table
name: テーブルの名前
Optional parameters:
schema: Name of the schema the table lies in.
schema: テーブルがあるスキーマの名前。
Example:
<?php
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Table;
#[Entity]
#[Table(name: "user", schema: "schema_name")]
class User { }
20.2.34. #[UniqueConstraint]¶
Attribute is used on
the entity-class level. It allows to hint the SchemaTool
to
generate a database unique constraint on the specified table
columns. It only has meaning in the SchemaTool schema generation
context.
Required parameters:
name: Name of the Index
name: インデックスの名前columns: Array of columns.
列: 列の配列。
Optional parameters:
options: Array of platform specific options:
options: プラットフォーム固有のオプションの配列:where
: SQL WHERE condition to be used for partial indexes. It will only have effect on supported platforms.where: 部分インデックスに使用する SQL WHERE 条件。サポートされているプラットフォームでのみ効果があります。
Basic example:
<?php
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\UniqueConstraint;
#[Entity]
#[UniqueConstraint(name: "ean", columns: ["ean"])]
class ECommerceProduct
{
}
20.2.35. #[Version]¶
Marker attribute that defines a specified column as version attribute used in
an optimistic locking
scenario. It only works on #[Column] attributes that have
the type integer
or datetime
. Setting #[Version]
on a property with
#[Id is not supported.
Example:
<?php
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Version;
#[Column(type: "integer")]
#[Version]
protected $version;