Jac*_*717 7 php symfony symfony-2.8
如何重写此代码以从表中获取最后插入的记录?
$repository = $entityManager->getRepository('AdminBundle:MyTable');
$product = $repository->find($id);
Run Code Online (Sandbox Code Playgroud)
我试过类似的东西
$repository->findBy(array('id','DESC')->setMaxResults(1);
Run Code Online (Sandbox Code Playgroud)
但它对我不起作用。
M K*_*aid 16
您可以通过使用findBy()order by、limit 和 offset 参数获取最新记录
$results = $repository->findBy(array(),array('id'=>'DESC'),1,0);
Run Code Online (Sandbox Code Playgroud)
请注意,它会将结果集作为对象数组返回,因此您可以从结果中获取单个对象 $results[0]
小智 9
您还可以创建一个存储库方法并在必要时调用它,而不是在您想要使用它的地方破解代码。
/**
* 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();
}
Run Code Online (Sandbox Code Playgroud)
参考资料:https : //symfony.com/doc/current/doctrine.html#querying-for-objects-the-repository
小智 5
在寻找了一个之后,我决定自己尝试一下,我认为它不那么冗长:
$myRepository->findOneBy([], ['id' => 'DESC']);
Run Code Online (Sandbox Code Playgroud)