我已经在我的Symfony应用程序中使用Doctrine Query Builder构建了以下查询。
$qb->select('c')
->from('AppBundle:Course', 'c')
->join('AppBundle:Log', 'a', ExprJoin::WITH, $qb->expr()->eq('c.id', 'a.course'))
->where($qb->expr()->in('a.type', ':type'))
->andWhere($qb->expr()->between('a.time', ':start', ':end'))
->andWhere($qb->expr()->eq('c.status', ':status'))
->setParameter(':type', ['opened'])
->setParameter(':standardScratchScore', [74])
->setParameter(':status', Course::OPENED)
->setParameter(':start', $dateFrom->format('Y-m-d H:i:s'))
->setParameter(':end', $dateTo->format('Y-m-d H:i:s'))
;
在我的代码中,我遍历Course
,然后再次查询Log
表以检查Course
不存在具有特定类型的条目。有没有办法将本课程的log.type = 'log.sent-email'
排除合并到此初始查询中,而无需使用子选择之类的内容?
在循环中再次查询同一个表对我来说感觉不是最佳的,NewRelic 建议它损害了我的应用程序的性能。
好吧,您始终可以针对此特定需求再次加入表:
$qb->select('c')
->from('AppBundle:Course', 'c')
->join('AppBundle:Log', 'a', ExprJoin::WITH, $qb->expr()->eq('c.id', 'a.course'))
->leftjoin(
'AppBundle:Log',
'b',
ExprJoin::WITH,
$qb->expr()->andx(
$qb->expr()->eq('c.id', 'b.course'),
$qb->expr()->eq('b.type', 'log.sent-email')
))
) // join log a second time, with the type condition
->where($qb->expr()->in('a.type', ':type'))
->andWhere($qb->expr()->between('a.time', ':start', ':end'))
->andWhere($qb->expr()->eq('c.status', ':status'))
->andWhere($qb->expr()->isNull('b.type')) // Only select records where no log record is found
->setParameter(':type', ['opened'])
->setParameter(':standardScratchScore', [74])
->setParameter(':status', Course::OPENED)
->setParameter(':start', $dateFrom->format('Y-m-d H:i:s'))
->setParameter(':end', $dateTo->format('Y-m-d H:i:s'))
;