在JOIN中将排除项添加到主义查询生成器中

问题描述 投票:0回答:1

我已在Symfony应用程序中使用“ Doctrine查询生成器”构建了以下查询。

    $qb->select('c')
        ->from('AppBundle:Course', 'c')
        ->join('AppBundle:Log', 'a', Expr\Join::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表示这正在损害我的应用程序的性能。

postgresql symfony join doctrine dql
1个回答
0
投票
嗯,您可以根据需要随时再加入一次表如果您在ORM配置中指定了课程和日志之间的关系,则不需要使用WITH子句进行连接(就像您在第一次日志连接中所做的那样)。

$qb->select('c') ->from('AppBundle:Course', 'c') ->join('AppBundle:Log', 'a', Expr\Join::WITH, $qb->expr()->eq('c.id', 'a.course')) ->leftjoin('AppBundle:Log', 'b', Expr\Join::WITH, $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('b.id IS NULL') // 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')) ;

© www.soinside.com 2019 - 2024. All rights reserved.