php 如何在 symfony2 中使用 DQL 获得单个结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11878075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:20:50 来源:igfitidea点击:
How can i get the single result using DQL in symfony2
提问by user17
I want to get the last user profile . But i am not able to do that in DQL. I have this code
我想获取最后一个用户配置文件。但我无法在 DQL 中做到这一点。我有这个代码
$em = $this->getEntityManager();
$dql = "SELECT p FROM AcmeBundle:UserProfile p
WHERE p.user_id = :user_id
ORDER BY p.createdAt DESC ";
$allProfiles = $em->createQuery($dql)
->setParameter('user_id', $user_id)
->setMaxResults(5)
->getResult();
return $allProfiles;
It returns all the profiles.
它返回所有配置文件。
If i use getSingleResult() then it says result not unique
如果我使用 getSingleResult() 那么它说结果不是唯一的
采纳答案by Carlos Granados
$allProfiles = $em->createQuery($dql)
->setParameter('user_id',$user_id)
->setMaxResults(1)
->getResult();
return $allProfiles[0];
回答by Nerjuz
The right method is:
正确的方法是:
$singleProfile = $em->createQuery($dql)
->setParameter('user_id',$user_id)
->getSingleResult();
To prevent error then no results try this:
为了防止错误然后没有结果试试这个:
$singleProfile = $em->createQuery($dql)
->setParameter('user_id',$user_id)
->getOneOrNullResult();

