Symfony2 QueryBuilder find first and find last record in table


Here i how to find first/last record in Symfony 2 using query builder :

Find Last

public function findLast() {
$qb = $this->createQueryBuilder(‘tc’);
$qb->setMaxResults( 1 );
$qb->orderBy(‘tc.id’, ‘DESC’);

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

 

Find First

public function findFirst() {
$qb = $this->createQueryBuilder(‘tc’);
$qb->setMaxResults( 1 );
$qb->orderBy(‘tc.id’, ‘ASC’);

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

 

in a Function

public function find($what) {

$order =(strtolower($what)==’asc’) ? $what : “desc”;
$qb = $this->createQueryBuilder(‘tc’);
$qb->setMaxResults( 1 );
$qb->orderBy(‘tc.id’,$order);

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

 

One thought on “Symfony2 QueryBuilder find first and find last record in table

  1. Find Last :

    $repository->findOneBy(array(), array(‘id’ => ‘DESC’));

    Find First :

    $repository->findOneBy(array(), array(‘id’ => ‘ASC’));

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s