symfony2 doctrine选择IFNULL

时间:2013-04-24 21:11:39

标签: symfony doctrine query-builder 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'

2 个答案:

答案 0 :(得分:32)

使用 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在列表中返回第一个非空值,因此如果A为空且B不为空,则COALESCE(A,B)将返回B.

答案 1 :(得分:4)

有一个Doctrine扩展可以添加其他功能。

这是来自IFNULL的DQL文件。 https://github.com/beberlei/DoctrineExtensions/blob/master/src/Query/Mysql/IfNull.php

本章介绍了如何使用它们。 http://symfony.com/doc/2.0/cookbook/doctrine/custom_dql_functions.html