phpsymfonysymfony-2.8

Symfony 2 - fetch the last inserted row from table


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.


Solution

  • 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);
    

    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