Mr. Smith Mr. Smith - 4 months ago 67
PHP Question

Symfony2, Doctrine2, findBy() order not working

I created a repository for my Articles entity and I'm trying to get all values ordered by ID DESC. But, I'll get everytime values ordered by id ASC. Here is my ArticleRepository.php:

<?php

namespace Acme\BlogBundle\Entity;

use Doctrine\ORM\EntityRepository;

class ArticleRepository extends EntityRepository
{
public function findAll()
{
return $this->findBy(array(), array('id' => 'DESC'));
}

public function findOneBySlug($slug)
{
$query = $this->getEntityManager()
->createQuery('
SELECT p FROM AcmePagesBundle:Article a
WHERE a.slug = :slug
')
->setParameter('slug', $slug);

try {
return $query->getSingleResult();
} catch (\Doctrine\ORM\NoResultException $e) {
return false;
}
}
}


Any ideas?

Answer

The Syntax looks good. This should provide a set of well ordered articles.

First, make sure the @Entity annotation is set with the right Repository class within the Article Entity,

/**
 * @ORM\Entity(repositoryClass="...");
 */
class Article
{
    // ...
}

Also, if you want to use native helpers, you've just to call findBy from the ArticleRepository within your controller,

 $articles = $this->get('doctrine')
      ->getRepository('YourBundle:Article')
      ->findBy(array(), array('id' => 'DESC'));