Reputation: 4835
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?
Upvotes: 5
Views: 35217
Reputation: 9652
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'));
....
}
Upvotes: 0
Reputation: 1487
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
Upvotes: 2
Reputation: 13891
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'));
Upvotes: 13
Reputation: 398
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.
Upvotes: 0
Reputation:
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();
}
Upvotes: 1