用学说2设置LIMIT?

bux*_*bux 52 doctrine-orm

我试图写一个查询(带子查询),但我不知道如何在我的子查询中设置限制.我的查询:

$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)
    ;
Run Code Online (Sandbox Code Playgroud)

但是- > setMaxResults(5)不起作用.SQL查询中没有'LIMIT'.我们可以用学说2做简单的限制吗?

Dar*_*ita 50

$query_ids = $this->getEntityManager()
      ->createQuery(
        "SELECT e_.id
        FROM MuzichCoreBundle:Element e_
        WHERE [...]
        GROUP BY e_.id")
     ->setMaxResults(5)
     ->setMaxResults($limit) 
    ;
Run Code Online (Sandbox Code Playgroud)

在第二个查询中,应该传递第一个查询的结果.

$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();
Run Code Online (Sandbox Code Playgroud)

  • 如果您在 DQL 中使用 JOIN,请务必小心。它不会按预期执行:http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#first-and-max-result-items -dql-仅查询 (2认同)

Osk*_*kar 18

我使用 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);
Run Code Online (Sandbox Code Playgroud)

  • 问题是如何限制子查询实体,例如相关实体。 (2认同)

spa*_*lls 6

您需要在对象上设置setMaxResults($ limit).

例如

$query_ids = $this->getEntityManager()
  ->createQuery(
    "SELECT e_.id
    FROM MuzichCoreBundle:Element e_
    WHERE [...]
    GROUP BY e_.id")
;
$query_ids->setMaxResults($limit);
Run Code Online (Sandbox Code Playgroud)

  • 为什么这有赞成票呢?它与OP完全相同,但它只是为同一个变量添加了更多的赋值 (8认同)
  • 在我的情况下不起作用.当我使用$ query_ids-> getDql()时,LIMIT丢失了. (3认同)