165

I am using the findBy() method on a Doctrine repository:

$entities = $repository->findBy(array('type'=> 'C12'));

How can I order the results?

Nic Wortel
  • 11,155
  • 6
  • 60
  • 79
Mirage
  • 30,868
  • 62
  • 166
  • 261

3 Answers3

349

The second parameter of findBy is for ORDER.

$ens = $em->getRepository('AcmeBinBundle:Marks')
          ->findBy(
             array('type'=> 'C12'), 
             array('id' => 'ASC')
           );
Tessmore
  • 1,054
  • 1
  • 9
  • 23
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • 7
    Apparently the API documentation on the doctrine website doesn't match the actual source code. https://github.com/doctrine/doctrine2/blob/2.4/lib/Doctrine/ORM/EntityRepository.php shows that you are correct. – Patrick James McDougle Oct 07 '13 at 15:12
  • Can I set mutliple order by ? – Fabien Papet Dec 17 '14 at 12:49
  • 9
    A little late finding this question, but for anyone else wondering about this, yes you can add multiple "order by", just add more elements in that second parameter array and define the field names 'ASC' or 'DESC'. IE: `array('priority'=>'ASC','id'=>'ASC')`. – Aaron Belchamber Mar 25 '15 at 14:41
  • 1
    What if AcmeBinBundle:Marks is related ManyToOne with "product" and we want to order by a field in product object? Is this posible? – Rodolfo Velasco Nov 18 '15 at 14:56
  • 2
    @RodolVelasco `findBy` is used for basic query scene, for more complicate scene, use query instead. like `$qb = $em->getRepository('AcmeBinBundle:Marks')->createQueryBuilder('m')->...`. – xdazz Nov 19 '15 at 01:07
  • is this also valid for findOneBy? – cwhisperer Jul 11 '19 at 06:39
31
$ens = $em->getRepository('AcmeBinBundle:Marks')
              ->findBy(
                 array(), 
                 array('id' => 'ASC')
               );
Jethik
  • 1,860
  • 1
  • 22
  • 26
14
$cRepo = $em->getRepository('KaleLocationBundle:Country');

// Leave the first array blank
$countries = $cRepo->findBy(array(), array('name'=>'asc'));
Bhaktaraz
  • 461
  • 5
  • 13