Search code examples
phpsymfonyquery-builderdoctrine-query

Symfony2 index of an object sorted by DQL


Hi I've done a simple query for a ranking mechanism with the query builder.

        $result = $qb
            ->select('u')
            ->where('u.status = 1')
            ->from('PGMainBundle:User', 'u')
            ->groupBy('u.id')
            ->addSelect('COUNT(c.id) as HIDDEN nChallenges')
            ->leftJoin('u.challenges', 'c', 'WITH', 'c.closed = 1' )
            ->add('orderBy','u.points DESC, nChallenges DESC')
            ->orderBy('u.points', 'DESC')
            ->addOrderBy('nChallenges', 'DESC')
            ->setFirstResult($offset*50)
            ->setMaxResults(50)
            ->getQuery()
            ->getResult();

Now while my ranking mechanism works fine, I'd like to check what loop.index a user with an $id has.

Said this, I don't want to use a foreach loop on the result to do so.

Is there a more optimal way just to return the "position" in the ranking ?

Possibly using the query builder ?


Solution

  • The result should be an array collection so you can get the index of a given element like this :

    $result->indexOf($yourelement)
    

    Else if the keys are not in order, but are the id of the entities :

      $keys = $result->getKeys();
      $id = $yourElement->getId();
      $position = array_search($id, $keys);