2017-01-18 6 views
3

である私は私のDBで、このデータを持っている:ドクトリン - symfonyの3 querybuilderのCOUNT()は間違っ

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:5では2でなく、foreign_id:1ではなくoccurrenceが2である理由は、なぜ発生が3であるのか見つかりません。 また、結果を別の時間にグループ化する方法はわかりません。

答えて

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; 
関連する問題