4

In question at Default sort attribute for Doctrine Model a .yml is suggested to define a default sorting for a collection-valued association.

I would like to have my models fetched by a default sorting, like following:

Foo:
    columns:
    ...
    options:
        orderBy: bar DESC

What is the annotation equivalent of this YAML-based setup?

Community
  • 1
  • 1
bob dope
  • 479
  • 1
  • 6
  • 16

1 Answers1

10

EDIT: This is not possible with defaults. Entities fetched from repositories are fetched by the provided sorting criteria:

$entities = $entityRepository->findBy(array(), array('field' => 'ASC'));

This, DQL and the Criteria API are the current ways of fetching entities with a given sorting criteria.

What the question at " Default sort attribute for Doctrine Model " is about is the sorting of collection-valued associations, which has nothing to do with direct fetching of entities from repositories.

For those associations, the annotation-equivalent of " Default sort attribute for Doctrine Model " is following (original answer):

As of the official annotations documentation for Doctrine 2 ORM, the annotation for default sorting conditions of collection-valued associations @OrderBy({"field" = "ASC", "otherField" = "DESC"}).

Here's how you would use it:

/**
 * @ORM\OneToMany(targetEntity="Users")
 * @ORM\OrderBy({"username" = "ASC"})
 */
protected $users;
Community
  • 1
  • 1
Ocramius
  • 25,171
  • 7
  • 103
  • 107
  • Thanks for your reply, but my question explicitly says: "Not just a relationship association, but the whole model". The link I mentioned is also pretty clear. – bob dope Feb 26 '13 at 14:31
  • @bobdope that's not supported by the ORM. If you want to fetch with a particular sorting, use `$repository->findBy(array(), array('username' => 'ASC'))`. Annotations and mappings for sorting only work on associations. You asked for the equivalent of the linked question: this answer is that equivalent. – Ocramius Feb 26 '13 at 14:34
  • I researched further and found that I misunderstood the question I linked to. You're 100% right, sorry about that. I validated your answer. – bob dope Feb 26 '13 at 14:49