How to sort findAll Doctrine's method?

前端 未结 12 2125
闹比i
闹比i 2020-12-23 00:14

I\'ve been reading Doctrine\'s documentation, but I haven\'t been able to find a way to sort findAll() Results.

I\'m using symfony2 + doctrine, this is the statemen

相关标签:
12条回答
  • 2020-12-23 00:57

    Try this:

    $em = $this->getDoctrine()->getManager();
    
    $entities = $em->getRepository('MyBundle:MyTable')->findBy(array(), array('username' => 'ASC'));
    
    0 讨论(0)
  • 2020-12-23 00:59

    Simple:

    $this->getDoctrine()->getRepository('AcmeBundle:User')->findBy(
        array(),
        array('username' => 'ASC')
    );
    
    0 讨论(0)
  • 2020-12-23 01:03

    Look at the Doctrine API source-code :

    class EntityRepository{
      ...
      public function findAll(){
        return $this->findBy(array());
      }
      ...
    }
    
    0 讨论(0)
  • 2020-12-23 01:04

    This works for me:

    $entities = $em->getRepository('MyBundle:MyTable')->findBy(array(),array('name' => 'ASC'));
    

    Keeping the first array empty fetches back all data, it worked in my case.

    0 讨论(0)
  • 2020-12-23 01:05

    I use an alternative to the solution that wrote nifr.

    $resultRows = $repository->fetchAll();
    uasort($resultRows, function($a, $b){
        if ($a->getProperty() == $b->getProperty()) {
            return 0;
        }
        return ($a->getProperty()< $b->getProperty()) ? -1 : 1;
    });
    

    It's quicker than the ORDER BY clause, and without the overhead of the Iterator.

    0 讨论(0)
  • 2020-12-23 01:06

    You can sort an existing ArrayCollection using an array iterator.

    assuming $collection is your ArrayCollection returned by findAll()

    $iterator = $collection->getIterator();
    $iterator->uasort(function ($a, $b) {
        return ($a->getPropery() < $b->getProperty()) ? -1 : 1;
    });
    $collection = new ArrayCollection(iterator_to_array($iterator));
    

    This can easily be turned into a function you can put into your repository in order to create findAllOrderBy() method.

    0 讨论(0)
提交回复
热议问题