Andy Holmes
Andy Holmes

Reputation: 8047

How to order results using EntityManager from Controller in Symfony2

I have this code:

public function indexAction()
{
    $em = $this->getDoctrine()->getManager();
    $user = $this->getUser();
    $entities = $em
        ->getRepository('BreedrGeckoBundle:Weight')
        ->findBy(array('user' => $user), array());

    return array(
        'entities' => $entities,
    );
}

Which is fine, gets all the weights in the database for the current user.
But how can I order the results so that all the weight entries for the same gecko id are together?
My table structure is as follows:

enter image description here

Upvotes: 3

Views: 1410

Answers (3)

rotelando
rotelando

Reputation: 11

You can also order by using the repository object itself like so:

public function indexAction()
{
    $em = $this->getDoctrine()->getManager();
    $user = $this->getUser();
    $entities = $em
        ->getRepository('BreedrGeckoBundle:Weight')
        ->findBy(array('user' => $user), array('geckoId' => 'ASC'));

    return array(
        'entities' => $entities,
    );
}

Upvotes: 1

MikO
MikO

Reputation: 18741

You need to query for your objects using Doctrine's QueryBuilder.
Something like this:

$repository = $this->getDoctrine()
    ->getRepository('BreedrGeckoBundle:Weight');

$query = $repository->createQueryBuilder('w')
    ->where('w.user = :user')
    ->orderBy('w.geckoId ASC')
    ->getQuery();

$query->setParameter(':user', $user);

$entities = $query->getResult();

If you want additional ordering, you can do something like:

->orderBy('w.geckoId ASC, w.weight ASC, w.id ASC')

Upvotes: 4

Alessandro Lai
Alessandro Lai

Reputation: 2274

You should create your own repository and use the addGroupBy function on the querybuilder. Example:

class WeightRepository extends EntityRepository
{
    public function getGroupedByGeckoId(User $user)
    {
        $qb = $this->createQueryBuilder('weight');

        $qb->select('whateverYouWant');
        $qb->andWhere('weight.user = :user');
        $qb->setParameter('user', $user);

        $qb->addGroupBy('weight.geckoId');

        return $qb->getQuery()->getResult();
    }
}

Upvotes: 3

Related Questions