DQL和SQL查询返回的数据多于QueryBuilder ......,怎么样?为什么呢?

时间:2017-05-24 18:17:33

标签: php doctrine-orm doctrine query-builder symfony-2.3

我在Doctrine Repository中有以下代码:

$em           = $this->getEntityManager();
$qb           = $em->createQueryBuilder();
$query_result = $qb->select('IDENTITY(l.customer) as customer, COUNT(l) AS total_unattached')
                   ->from('QuoteBundle:License', 'l')
                   ->leftJoin('QuoteBundle:Agreement', 'a', Join::WITH, $qb->expr()->andX(
                       'l.agreementType = a.agreementType',
                       'l.customer = a.customer'
                   ))
                   ->where('l.customer IN (:implode)')
                   ->setParameter('implode', implode(',', $customers_id))
                   ->andWhere('a.agreementNumber IS NULL')
                   ->groupBy('l.customer')
                   ->getQuery()
                   ->getArrayResult();

如果我count($query_result),请从上面的代码中获得1

  

计数($ query_result)       < 1

现在有趣的事情如下:

我已尝试过上一个查询构建器生成的DQL $qb->getDQL()

SELECT
  IDENTITY(l.customer) AS customer,
  COUNT(l)             AS total_unattached
FROM
  QuoteBundle:License l
LEFT JOIN QuoteBundle:Agreement a WITH l.agreementType = a.agreementType AND l.customer = a.customer
WHERE l.customer IN (21, 23) AND a.agreementNumber IS NULL GROUP BY l.customer

我惊讶地得到了两个值:

array (size=2)
  0 => 
    array (size=2)
      'customer' => string '21' (length=2)
      'total_unattached' => string '1' (length=1)
  1 => 
    array (size=2)
      'customer' => string '23' (length=2)
      'total_unattached' => string '17' (length=2)

我尝试过上一个查询构建器生成的SQL $qb->getQuery()->getSQL()

SELECT
  l0_.CustomerSiteID AS sclr_0,
  COUNT(l0_.id)      AS sclr_1
FROM license l0_
  LEFT JOIN agreement a1_
    ON (l0_.AgreementTypeID = a1_.AgreementTypeID AND l0_.CustomerSiteID = a1_.CustomerSiteID)
WHERE l0_.CustomerSiteID IN (21, 23) AND a1_.AgreementNumber IS NULL
GROUP BY l0_.CustomerSiteID

我很惊讶我再次 2个值:

21  1
23  17

以下是以下陈述的结果:

dump($qb->getParameters());
dump($qb->getDQL());
dump($qb->getQuery()->getSQL());
dump($query_result);

enter image description here

有了这个,为什么$query_result只有一个?

更新

我也试过了getResult()而不是getArrayResult(),结果是一样的,见下图:

enter image description here

注意前一个QB生成的查询如何返回两行而不是一行:

enter image description here

1 个答案:

答案 0 :(得分:2)

问题在于以:implode发送的参数 - 您正在发送字符串"21,23",然后仅将其解析为数字21,删除第二个ID。众所周知,MySQL会这样做(有一个你在这里看不到的警告)。

从正在准备的SQL语句中可以看出 - l0.CustomerSiteID IN (?)条件只包含一个?,但它应该看起来像(?, ?)才能正常工作。

直接使用数组,不使用 imploding 。 QB应该处理它并生成正确的SQL。