24

When using a Doctrine_Table object, is it possible to specify the order of the returned collection when using findAll() or findByWhatever()?

In the doc's I see some stuff about getOrderByStatement() and processOrderBy() but it isn't clear on how to use them...

Jake Wilson
  • 88,616
  • 93
  • 252
  • 370

4 Answers4

60

You can also leave the first array blank

  $em->getRepository('BackendDestinyBundle:Destiny')->findBy(array(), array('title'=>'asc'));
Ari
  • 934
  • 1
  • 10
  • 15
  • Ok my bad, don't cry please just trying to help – Ari Mar 25 '13 at 13:30
  • 1
    Thank you. This is what I wanted. Quick, simple and works a treat. – dnshio Jul 01 '13 at 15:33
  • this is actually better than the query builder (in my opinion), after all, the implementation of ``findAll()`` is a call like this ``findBy(array())`` here's the [source code](http://www.doctrine-project.org/api/orm/2.3/source-class-Doctrine.ORM.EntityRepository.html#149-171) – Mateo Torres Sep 27 '13 at 21:40
  • 1
    Thank you! I just used this: `public function findAll() { return $this->findBy(array(), array('name' => 'ASC')); }` To quickly overwrite the findAll order returned for a form return of a entity. – Scott Flack Oct 25 '13 at 04:30
13

You can in fact specify a default order by in your schema:

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

Note that when you want to specify a different order, you can still create a query and override the default order by.

Gerry
  • 6,012
  • 21
  • 33
6

According to Jon Wage you should create a Query in this Case… Found in the mailing-list

Flask
  • 4,966
  • 1
  • 20
  • 39
1

In my case, the problem was that i had a statement like this

$destinos  = $em->getRepository('BackendDestinyBundle:Destiny')->findAll();

finaly I changed it to a CreateQuery statement, it does exactly the same but i can put a OrderBy sentence

$destinos  = $em->createQuery("SELECT d FROM BackendDestinyBundle:Destiny d order by d.name")->getResult();
j0k
  • 22,600
  • 28
  • 79
  • 90
  • 2
    You are talking about Doctrine 2 here, and by the way, this isn't the good way to use Doctrine. Should build a query without writing sql code ... You are loosing all advantage from the ORM here... – j0k Mar 14 '13 at 18:36
  • 9
    Actually he's using ORM quite good here since it's DQL, not SQL. – Łukasz Wojciechowski Sep 22 '13 at 12:19