2013-04-24 63 views
10

好吧,我有這樣的代碼:Symfony2的原則選擇IFNULL

SELECT 
IFNULL(s2.id,s1.id) AS effectiveID, 
IFNULL(s2.status, s1.status) AS effectiveStatus, 
IFNULL(s2.user_id, s1.user_id) as effectiveUser, 
IFNULL(s2.likes_count, s1.likes_count) as effectiveLikesCount 

FROM statuses AS s1 
LEFT JOIN statuses AS s2 ON s2.id = s1.shared_from_id 
WHERE s1.user_id = 4310 
ORDER BY effectiveID DESC 
LIMIT 15 

,我需要重寫它的QueryBuilder。像那樣的東西?

 $fields = array('IFNULL(s2.id,s1.id) AS effectiveID','IFNULL(s2.status, s1.status) AS effectiveStatus', 'IFNULL(s2.user_id, s1.user_id) as effectiveUser','IFNULL(s2.likes_count, s1.likes_count) as effectiveLikesCount'); 

    $qb=$this->_em->createQueryBuilder() 
      ->select($fields) 
      ->from('WallBundle:Status','s1') 
      ->addSelect('u') 
      ->where('s1.user = :user') 
      ->andWhere('s1.admin_status = false') 
      ->andWhere('s1.typ_statusu != :group') 
      ->setParameter('user', $user) 
      ->setParameter('group', 'group') 
      ->leftJoin('WallBundle:Status','s2', 'WITH', 's2.id=s1.shared_from_id') 
      ->innerJoin('s1.user', 'u')    
      ->orderBy('s1.time', 'DESC') 
      ->setMaxResults(15); 

    var_dump($query=$qb->getQuery()->getResult());die(); 

此錯誤是

[Syntax Error] line 0, col 7: Error: Expected known function, got 'IFNULL' 
+0

是的,就像錯誤信息說的 - 原則查詢語言不知道這樣的功能。找到類似問題的答案http://stackoverflow.com/a/9110213/1727046 – gatisl 2013-04-24 21:35:15

+0

@gatisl是的先生,我看到它,但我不知道...我怎麼能「安裝」它? – EnchanterIO 2013-04-24 22:56:30

回答

24

使用COALESCE,而不是IFNULL這樣

$fields = array('COALESCE(s2.id,s1.id) AS effectiveID','COALESCE(s2.status, s1.status) AS effectiveStatus', 'COALESCE(s2.user_id, s1.user_id) as effectiveUser','COALESCE(s2.likes_count, s1.likes_count) as effectiveLikesCount'); 

COALESCE返回列表中的非空的值,因此,如果是空, B不爲空,則COALESCE(A,B)將返回B.