Ordering To-Many Associations

There are use-cases when you’ll want to sort collections when they are retrieved from the database. In userland you do this as long as you haven’t initially saved an entity with its associations into the database. To retrieve a sorted collection from the database you can use the #[OrderBy] attribute with a collection that specifies a DQL snippet that is appended to all queries with this collection.

コレクションがデータベースから取得されたときにコレクションを並べ替えたい場合があります。ユーザーランドでは、最初にエンティティをその関連付けとともにデータベースに保存していない限り、これを行います。データベースからソートされたコレクションを取得するには、#[OrderBy] 属性をコレクションで使用して、このコレクションを持つすべてのクエリに追加される DQL スニペットを指定します。

Additional to any #[OneToMany] or #[ManyToMany] attribute you can specify the #[OrderBy] in the following way:

#[OneToMany] または #[ManyToMany] 属性に加えて、次の方法で #[OrderBy] を指定できます。

The DQL Snippet 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.

OrderBy の DQL スニペットは、修飾も引用符も付けられていないフィールド名と、オプションの ASC/DESC 位置ステートメントのみで構成できます。複数のフィールドはコンマ (,) で区切ります。参照されるフィールド名は、#[ManyToMany] または #[OneToMany] 属性の targetEntityclass に存在する必要があります。

The semantics of this feature can be described as follows:

この機能のセマンティクスは次のように説明できます。

  • @OrderBy acts as an implicit ORDER BY clause for the given fields, that is appended to all the explicitly given ORDER BY items.

    @OrderBy は、指定されたフィールドの暗黙の ORDER BY 句として機能し、明示的に指定されたすべての ORDER BY 項目に追加されます。

  • All collections of the ordered type are always retrieved in an ordered fashion.

    順序付けられた型のすべてのコレクションは、常に順序付けられた方法で取得されます。

  • To keep the database impact low, these implicit ORDER BY items are only added to a DQL Query if the collection is fetch joined in the DQL query.

    データベースへの影響を低く抑えるために、これらの暗黙的な ORDER BY 項目は、コレクションが DQL クエリでフェッチ結合されている場合にのみ DQL クエリに追加されます。

Given our previously defined example, the following would not add ORDER BY, since g is not fetch joined:

前に定義した例を考えると、g はフェッチ結合されていないため、以下は ORDER BY を追加しません。

SELECT u FROM User u JOIN u.groups g WHERE SIZE(g) > 10

However the following:

ただし、次のとおりです。

SELECT u, g FROM User u JOIN u.groups g WHERE u.id = 10

…would internally be rewritten to:

…内部的に次のように書き換えられます。

SELECT u, g FROM User u JOIN u.groups g WHERE u.id = 10 ORDER BY g.name ASC

You can reverse the order with an explicit DQL ORDER BY:

明示的な DQL ORDER BY を使用して順序を逆にすることができます。

SELECT u, g FROM User u JOIN u.groups g WHERE u.id = 10 ORDER BY g.name DESC

…is internally rewritten to:

…内部的に次のように書き換えられます。

SELECT u, g FROM User u JOIN u.groups g WHERE u.id = 10 ORDER BY g.name DESC, g.name ASC

Previous topic

Composite and Foreign Keys as Primary Key

主キーとしての複合キーと外部キー

Next topic

Override Field Association Mappings In Subclasses

サブクラスでのフィールド関連付けマッピングのオーバーライド

This Page

Fork me on GitHub