SUM函数中的条件

时间:2015-09-22 12:32:27

标签: php symfony doctrine-orm

我有一个与User实体有one-to-many关系的Certificate实体(一个用户可能有多个证书)。 Certificate有一个startDateendDate,用于确定其有效期。我需要过滤所有已过期证书且没有活动证书的用户 有效证书 - c.startDate <= :today AND c.endDate > :today
过期的证书 - c.endDate <= :today

我现在如何在纯SQL中执行此操作:

SELECT
  u.user_id
FROM `User` u JOIN `Certificate` c ON c.user_id = u.user_id
GROUP BY u.user_id
HAVING SUM(c.end_date > :today) = 0

现在我尝试将SQL查询移植到Doctrine QueryBuilder语法:

$qb = $this->createQueryBuilder();
$qb
    ->from('SomeNS:User', 'u')
    ->select('u')
    ->join('u.certificates', 'c')
    ->groupBy('u.id')
    ->having('SUM(c.endDate > :today) = 0')
    ->setParameter('today', $today);

但是会发生错误:

  

错误:预期的Doctrine \ ORM \ Query \ Lexer :: T_CLOSE_PARENTHESIS,得到&#39;&lt;&#39;

看起来学说中没有理解SUM函数中的条件 请帮助弄清楚如何在SUM函数中使用条件或指出我做错了什么。

1 个答案:

答案 0 :(得分:1)

以下是使用queryBuilder的expr()方法的具体答案:

---
->having(
  $qb->expr()->andx( // this is the "AND" in between the sums
    $qb->expr()->lte( // this is the "<="
      ...(your SUM here, after you fix the logic),
      0
    ),
    $qb->expr()->eq( // this is the "="
      ...(your SUM here, after you fix the logic),
      0
    )
  )
)

一旦你得到那些&#34; SUM&#34;条件正确,你把它们放在占位符中,它应该工作。