2014-08-28 53 views
2

我有一個表頁面上的用戶活動(字段:ID,USER_ID,PAGE_ID,日,投票,評論)Symfony2中,Doctrine2查詢 - 選擇具有IF和COUNT

"SELECT COUNT(DISTINCT m.user_id) as cnt, 
COUNT(DISTINCT IF(m.votes > 0, m.user_id, NULL)) as vote , 
COUNT(DISTINCT IF(m.comments > 0, m.user_id, NULL)) as comment, 
COUNT(DISTINCT IF(m.votes + m.comments > 0, m.user_id, NULL)) as votecomment 
FROM mytable m 
WHERE m.page_id = ".$user_id." 
AND m.day > '".$day."'" 

我想把它轉換成以我的Doctrine2查詢

//in EntityRepository class: 
$selectArr = array(
    'cnt' => "COUNT(DISTINCT m.user_id) as cnt", 
    'vote' => "COUNT(DISTINCT CASE WHEN (m.votes > 0) THEN m.user_id ELSE NULL END) as votes", 
    'comment' => "COUNT(DISTINCT CASE WHEN (m.comments > 0) THEN m.user_id ELSE NULL END) as comment", 
    'votecomment' => "COUNT(DISTINCT CASE WHEN (m.votes + m.comments > 0) THEN m.user_id ELSE NULL END) as votecomment", 
); 

$query = $this->createQueryBuilder('m') 
->select($selectArr) 
->where('m.page_id = :id') 
->andWhere('m.day > :from') 
->setParameter('id', $user_id) 
->setParameter('from', $day) 
->getQuery(); 
try { 
    return $query->getSingleResult(\Doctrine\ORM\Query::HYDRATE_ARRAY); 
} catch (\Doctrine\ORM\NoResultException $e) { 
    return null; 
} 

但它不起作用。爲什麼?如何解決它?

回答

2

對於複雜的查詢,您可以使用nativeQuery和ResultSetMapping。

$rsm = new ResultSetMapping(); 
    $rsm->addScalarResult('cnt', 'cnt', 'integer'); 
    $rsm->addScalarResult('vote', 'vote', 'integer'); 
    $rsm->addScalarResult('comment', 'comment', 'integer'); 
    $rsm->addScalarResult('votecomment', 'votecomment', 'integer'); 

    $query = $this->getEntityManager()->createNativeQuery("SELECT COUNT(DISTINCT m.user_id) as cnt, 
     COUNT(DISTINCT IF(m.votes > 0, m.user_id, NULL)) as vote , 
     COUNT(DISTINCT IF(m.comments > 0, m.user_id, NULL)) as comment, 
     COUNT(DISTINCT IF(m.votes + m.comments > 0, m.user_id, NULL)) as votecomment 
     FROM mytable m 
     WHERE m.page_id = :uid 
     AND m.day > :day", $rsm); 

    $query->setParameters([ 
     'uid' => $user_id, 
     'day' => $day, 
    ]); 

    $rows = $query->getResult(); 
+0

非常感謝! :) – Marzena 2014-08-28 13:16:00