Doctrine2如何创建聚合子查询

时间:2016-08-30 09:07:45

标签: php symfony doctrine-orm dql

我有下一张桌子

id int not null auto icrement
email_name varchar
event_type varchar

电子邮件类型 - 可能的值(已发送,打开,点击,取消订阅) 我需要在doctrine2

中创建这样的查询
SELECT COUNT(ee.id) as total, (SELECT COUNT(e.id) from email_statistic as e where e.event_type = 'open') as opened FROM email_statistic as ee

我想选择总金额,以及打开统计数据的电子邮件数量 我怎么能做这个wia学说?

   $qb = $this->createQueryBuilder('ee')
            ->select('count(ee) As total');

$qb2 = $this->createQueryBuilder('e')
            ->select('count(e) As opened');

        $qb2
            ->andWhere('es.eventType = :eventType')
            ->setParameter('eventType', 'open');

$qb->addSelect($qb2) --- this does not allowed by doctrine

我应该使用NATIVE QUERY吗?我可以用dql做这个吗?

1 个答案:

答案 0 :(得分:1)

首先,您应该创建一个实体,例如EmailStatistic:

/**
 * @ORM\Entity()
 * @ORM\Table()
 */
class EmailStatistic
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(name="email_type", type="string", length=255)
     */
    protected $emailType;

    /**
     * @var string
     *
     * @ORM\Column(name="email_name", type="string", length=255)
     */
    protected $emailName;
}

然后您可以使用GeneralCaseExpression(http://www.doctrine-project.org/api/orm/2.4/class-Doctrine.ORM.Query.AST.GeneralCaseExpression.html)。

$em = $this->get('doctrine')->getEntityManager();
$qb = $em->createQueryBuilder();
$result = $qb
    ->select('SUM(CASE WHEN (e.emailType = \'open\') THEN 1 ELSE 0 END) as opened')
    ->addSelect('SUM(e.id) as total')
    ->from('AppBundle:EmailStatistic', 'e')
    ->getQuery()
    ->getArrayResult();
// $result[0]['opened'] contains number of opened emails
// $result[0]['total'] contains total number of emails