symfony2 doctrine select IFNULL
Asked Answered
A

2

15

Ok i have this code:

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

And i need to rewrite it to querybuilder. Something like that?

        $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();

This error is

[Syntax Error] line 0, col 7: Error: Expected known function, got 'IFNULL'
Alibi answered 24/4, 2013 at 21:11 Comment(2)
Yes, just like error message is saying - Doctrine query language does not know such function. Found answer to a similar question https://mcmap.net/q/821895/-ifnull-in-symfony2-doctrine-query-builderCanada
@Canada yes sir, i saw it but i dont know... how can i "install" it ?Alibi
L
41

Use COALESCE instead of IFNULL like this

$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 return the first value not null in the list, so if A is null and B not null, then COALESCE(A,B) will return B.

Laconia answered 28/8, 2013 at 9:43 Comment(1)
You saved my day ! I used your solution to replace a CASE WHEN in an ORDER BY.Bootleg
R
5

There is a Doctrine extension that adds this among others.

This is the DQL file from IFNULL. https://github.com/beberlei/DoctrineExtensions/blob/master/src/Query/Mysql/IfNull.php

This chapter explains how you use them. http://symfony.com/doc/2.0/cookbook/doctrine/custom_dql_functions.html

Ramulose answered 5/2, 2014 at 15:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.