Symfony 2 - fetch the last inserted row from table

Jacek717 picture Jacek717 · Jan 3, 2018 · Viewed 11.1k times · Source

How can I rewrite this code in order to get last inserted record from the table?

$repository = $entityManager->getRepository('AdminBundle:MyTable');
$product = $repository->find($id);

I tried something like

$repository->findBy(array('id','DESC')->setMaxResults(1);

But it did not work for me.

Answer

M Khalid Junaid picture M Khalid Junaid · Jan 3, 2018

You could get the latest record by using findBy() with order by, limit and offset parameters

$results = $repository->findBy(array(),array('id'=>'DESC'),1,0);
  • First argument is for filter criteria
  • Second argument takes order by criteria
  • Third argument is for limit
  • Fourth argument sets offset

Note it will return you the results set as array of objects so you can get single object from result as $results[0]

FindBy() Examples