How can I get a single result using DQL in symfony2

I want to get the latest user profile. But I can not do this in DQL. I have this code

$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 profiles.

If I use getSingleResult () then it says the result is not unique

+7
source share
2 answers
  $allProfiles = $em->createQuery($dql) ->setParameter('user_id',$user_id) ->setMaxResults(1) ->getResult(); return $allProfiles[0]; 
+3
source

The correct method is:

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

To prevent an error, no results will try this:

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

All Articles