【问题标题】:How can i get the single result using DQL in symfony2如何在 symfony2 中使用 DQL 获得单个结果
【发布时间】:2012-08-06 08:43:10
【问题描述】:

我想获取最后一个用户配置文件。但我无法在 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;

它返回所有配置文件。

如果我使用 getSingleResult() 那么它说结果不是唯一的

【问题讨论】:

  • 您尝试过更改setMaxResult(1) 吗?
  • 我也尝试过 result(1) ,但这也返回了数组而不是单个对象
  • setMaxResults(1) 工作正常...

标签: php symfony doctrine


【解决方案1】:

正确的方法是:

$singleProfile = $em->createQuery($dql)
                    ->setParameter('user_id',$user_id)
                    ->getSingleResult();

为了防止错误然后没有结果试试这个:

$singleProfile = $em->createQuery($dql)
                    ->setParameter('user_id',$user_id)
                    ->getOneOrNullResult();

【讨论】:

  • 如果查询在ID以外的字段并且查询返回多条记录,getOneOrNullResult返回错误。例如,是否有一个函数只返回第一个?
  • 第一个例子在多行时返回More than one result was found for query although one row or none was expected.
【解决方案2】:
                $allProfiles = $em->createQuery($dql)
                                ->setParameter('user_id',$user_id)
                                ->setMaxResults(1)
                                ->getResult();
                return $allProfiles[0];

【讨论】:

  • 如果 $allProfiles 无效会发生什么?
  • 然后使用这个:if (empty($allProfiles)===true) { return null } else { return allProfiles[0]; } 而不是最后一行
猜你喜欢
  • 2014-06-03
  • 1970-01-01
  • 2013-05-26
  • 1970-01-01
  • 1970-01-01
  • 2020-07-07
  • 1970-01-01
  • 2013-12-13
  • 1970-01-01
相关资源
最近更新 更多