How to get the previous and next object through the object manager

Here's how I can get a custom object using its id:

$userEntity = $em->getRepository('ModelBundle:User')->find($userId);

Is there a way to get the previous and next entity based on this $ userEntity?

For example: I chose $ userEntity and its identifier is 100, now I want to get the previous entity regardless of its identifier 99, 80, 70, whatever that is! the same with the case with the following entity.

I can already find the next and previous using some kind of PHP hack, however I am looking for a better approach.

Edited: To clarify, I'm looking for an object-oriented approach, something like below:

$userEntity = $em->getRepository('ModelBundle:User')->find($userId);
$previousUserEntity = $userEntity->previous(); //example
$previousUserEntity = $userEntity->next(); //example

, userEntity - , previous() next(), , - , - !

+4
2

, , , .

, :

70
80
99
100

99, , <<22 > 99. :

public function getPreviousUser($userId)
{
    $qb = $this->createQueryBuilder('u')
        ->select('u')

        // Filter users.
        ->where('u.id < :userId')
        ->setParameter(':userId', $userId)

        // Order by id.
        ->orderBy('u.id', 'DESC')

        // Get the first record.
        ->setFirstResult(0)
        ->setMaxResults(1)
    ;

    $result = $qb->getQuery()->getOneOrNullResult();
}

:

$em->getRepository('ModelBundle:User')->getPreviousUser($userId);

80.


99, , , id , 99:

public function getNextUser($userId)
{
    $qb = $this->createQueryBuilder('u')
        ->select('u')

        ->where('u.id > :userId')
        ->setParameter(':userId', $userId)

        ->orderBy('u.id', 'ASC')

        ->setFirstResult(0)
        ->setMaxResults(1)
    ;

    $result = $qb->getQuery()->getOneOrNullResult();
}

:

$em->getRepository('ModelBundle:User')->getNextUser($userId);

id 100.

+3

funstion

public function previous(User $user)
{
    return $this->getEntityManager()
        ->createQuery(
            'SELECT u
            FROM ModelBundle:User u
            WHERE u.id = (SELECT MAX(us.id) FROM ModelBundle:User us WHERE us.id < :id )'
        )
        ->setParameter(':id', $user->getId())
        ->getOneOrNullResult();
}

public function next(User $user)
{
    return $this->getEntityManager()
        ->createQuery(
            'SELECT u
            FROM ModelBundle:User u
            WHERE u.id = (SELECT MIN(us.id) FROM ModelBundle:User us WHERE us.id > :id )'
        )
        ->setParameter(':id', $user->getId())
        ->getOneOrNullResult();
}
+6

All Articles