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
#[OrderBy] attribute with a collection that specifies
a DQL snippet that is appended to all queries with this
Additional to any
#[ManyToMany] attribute you
can specify the
#[OrderBy] in the following way:
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
class of the
The semantics of this feature can be described as follows:
@OrderByacts as an implicit ORDER BY clause for the given fields, that is appended to all the explicitly given ORDER BY items.
- 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.
Given our previously defined example, the following would not add ORDER BY, since g is not fetch joined:
1 SELECT u FROM User u JOIN u.groups g WHERE SIZE(g) > 10
However the following:
1 SELECT u, g FROM User u JOIN u.groups g WHERE u.id = 10
...would internally be rewritten to:
1 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:
1 SELECT u, g FROM User u JOIN u.groups g WHERE u.id = 10 ORDER BY g.name DESC
...is internally rewritten to:
1 SELECT u, g FROM User u JOIN u.groups g WHERE u.id = 10 ORDER BY g.name DESC, g.name ASC