Doctrine - Symfony 3 querybuilder COUNT()是错误的

时间:2017-01-18 17:00:29

标签: sql doctrine-orm symfony

我的数据库中有这些数据:

my data

我尝试使用guest_identifier的最新created_at值获取foreign_ids。

在这种情况下,我希望:

    foreign_id: 5 for guest_identifier: 12345
    foreign_id: 5 for guest_identifier: 2345
    foreign_id: 4 for guest_identifier: 345

现在我想计算这个结果并返回类似的内容:

[
   {
       "foreign_id": 5,
       "occurrence": 2
   },
   {
       "foreign_id": 4,
       "occurrence": 1
   }
]

这就是我尝试获得此结果的方法:

$qb = $this->createQueryBuilder('statistic')
        ->select('statistic.foreignId, COUNT(statistic.foreignId) as occurrence')
        ->where('statistic.guideId = :guideId')
        ->andWhere('statistic.type = :type')
        ->andWhere('statistic.createdAt BETWEEN :startDate AND :endDate')
        ->groupBy('statistic.guestIdentifier')
        ->setParameters(array(
            'guideId' => $guideId,
            'type' => 'answer_clicked',
            'startDate' => $startDate,
            'endDate' => $endDate
        ))
        ->getQuery();

    $stats = $qb->getResult();

    return $stats;

问题是,我的结果如下:

[
  {
    "foreignId": 5,
    "occurrence": "3"
  },
  {
    "foreignId": 5,
    "occurrence": "3"
  },
  {
    "foreignId": 4,
    "occurrence": "2"
  }
]

我无法找到,为什么对于foreign_id,为3,而不是2,为什么对于foreign_id,为什么出现为2而不是1:3。 我也不喜欢'知道如何将结果分组另一次。

1 个答案:

答案 0 :(得分:1)

我可以用这个答案来解决我的问题:https://stackoverflow.com/a/28090544/7069057

我的功能现在看起来像这样:

$qb = $this->createQueryBuilder('statistic')
        ->select('statistic.foreignId, COUNT(statistic.foreignId)')
        ->where('statistic.guideId = :guideId')
        ->andWhere('statistic.type = :type')
        ->andWhere('statistic.createdAt BETWEEN :startDate AND :endDate')
        ->leftJoin('AppBundle\Entity\Statistic\Statistic', 'stat', Join::WITH,
            'statistic.type = stat.type AND statistic.guestIdentifier = stat.guestIdentifier AND stat.createdAt > statistic.createdAt')
        ->andWhere('stat.createdAt IS NULL')
        ->groupBy('statistic.foreignId')
        ->setParameters(array(
            'guideId' => $guideId,
            'type' => 'answer_clicked',
            'startDate' => $startDate,
            'endDate' => $endDate
        ))
        ->getQuery();

    $stats = $qb->getResult();

    return $stats;