Symfony 2 - 从表中获取最后一个插入的行

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.

You could get the latest record by using findBy() with order by and limit paramters

$results = $repository->findBy(array(),array('id'=>'DESC'),0,1);
  • 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

Please try the below one

$repository = $entityManager->getRepository('AdminBundle:MyTable');
$repository->setMaxResults(1)->orderBy('id', 'DESC');
$results = $repository->getQuery()->getSingleResult();

Reference: https://undebugable.wordpress.com/2016/01/27/symfony2-querybuilder-find-first-and-find-last-record-in-table/

Instead of hacking code where you want to use it, you can also create a repository method and call it when necessary.

/**
 * Repository method for finding the newest inserted
 * entry inside the database. Will return the latest
 * entry when one is existent, otherwise will return
 * null.
 *
 * @return MyTable|null
 */
public function findLastInserted()
{
    return $this
        ->createQueryBuilder("e")
        ->orderBy("id", "DESC")
        ->setMaxResults(1)
        ->getQuery()
        ->getOneOrNullResult();
}

References: https://symfony.com/doc/current/doctrine.html#querying-for-objects-the-repository