简体   繁体   中英

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?

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'));

You don't need to create a query in ArticleRepostory.php for that

In your controller you can just do:

$entities = $em->getRepository('YourBundle:Article')->findBy(array(), array( 'id' => 'DESC' ));

->findBy(array(), array( 'id' => 'DESC' )); // Order Works  
->findAll(array(), array( 'id' => 'DESC' )); // Order doesn't work

This should be work:

public function findAll()
{
    $em = $this->getEntityManager();

    $query = $em->createQuery('
        SELECT *
        FROM AcmePagesBundle:Article a
        ORDER BY a.id DESC
    ');

    return $query->getResult();
}

I would tend to do this in my repository (to allow for using the same select DQL in different methods in the repository - especially when you have lots of fetch-joins to include):

class FooRepository extends EntityRepository
{
    /**
     * Get the DQL to select Foos with all joins
     *
     * @return string
     */
    public function getSelectDql()
    {
        $dql = '
               SELECT f
                 FROM Entity:Foo f
        ';

        return $dql;
    }

    /**
     * Fetch all foos, ordered
     *
     * @return array
     */
    public function fetchAllOrdered()
    {
        $dql = sprintf(
            '%s %s',
            $this->getSelectDql(),
            'ORDER BY f.id DESC'
        );

        return $this->getEntityManager()
            ->createQuery($dql)
            ->getResult();
    }
}

This should make your repository quite flexible, allow different ordering in different methods (if you need to order them differently) and keep all DB-related code out of your controller.

Symfony 3.3 find by order working example.

From your controller:

public function indexAction(){
     $entityManager = $this->getDoctrine()->getManager();
     $categoryRepository = $entityManager->getRepository(ProductCategory::class); 
     $items = $categoryRepository->findBy(array(), array('id' => 'DESC'));
     ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM