我尝试编写一个查询(带子查询),但我不知道如何在子查询中设置限制。 我的问题:
$query_ids = $this->getEntityManager()
->createQuery(
"SELECT e_.id
FROM MuzichCoreBundle:Element e_
WHERE [...]
GROUP BY e_.id")
->setMaxResults(5)
;
$query_select = "SELECT e
FROM MuzichCoreBundle:Element e
WHERE e.id IN (".$query_ids->getDql().")
ORDER BY e.created DESC, e.name DESC"
;
$query = $this->getEntityManager()
->createQuery($query_select)
->setParameters($params)
;
但 - > setMaxResults(5)不起作用。 SQL查询中没有'LIMIT'。我们可以用学说2做简单的限制吗?
答案 0 :(得分:49)
$query_ids = $this->getEntityManager()
->createQuery(
"SELECT e_.id
FROM MuzichCoreBundle:Element e_
WHERE [...]
GROUP BY e_.id")
->setMaxResults(5)
->setMaxResults($limit)
;
在第二个查询中,应该传递第一个查询的结果..
$query_select = "SELECT e
FROM MuzichCoreBundle:Element e
WHERE e.id IN (".$query_ids->getResult().")
ORDER BY e.created DESC, e.name DESC"
;
$query = $this->getEntityManager()
->createQuery($query_select)
->setParameters($params)
->setMaxResults($limit);
;
$resultCollection = $query->getResult();
答案 1 :(得分:16)
我为此使用 Doctrine\ORM\Tools\Pagination\Paginator
,它完美地运作(学说2.2)。
$dql = "SELECT p, c FROM BlogPost p JOIN p.comments c";
$query = $entityManager->createQuery($dql)
->setFirstResult(0)
->setMaxResults(10);
$paginator = new Paginator($query, $fetchJoinCollection = true);
答案 2 :(得分:6)
您需要在对象上设置 setMaxResults($ limit)。
e.g。
$query_ids = $this->getEntityManager()
->createQuery(
"SELECT e_.id
FROM MuzichCoreBundle:Element e_
WHERE [...]
GROUP BY e_.id")
;
$query_ids->setMaxResults($limit);
答案 3 :(得分:0)
$limit=5; // for exemple
$query = $this->getDoctrine()->getEntityManager()->createQuery(
'// your request')
->setMaxResults($limit);
$results = $query->getResult();
// Done
答案 4 :(得分:0)
$qb = $this->getDoctrine()->getManager()->createQueryBuilder();
$qb->select('p') ->from('Pandora\UserBundle\Entity\PhoneNumber', 'p');
$qb->where('p.number = :number');
$qb->OrWhere('p.validatedNumber=:number');
$qb->setMaxResults(1);
$qb->setParameter('number',$postParams['From'] );
$result = $qb->getQuery()->getResult();
$data=$result[0];