Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using IS NULL and COALESCE in OrderBy Doctrine Querybuilder

I basically have the following (My)SQL-Query

SELECT * FROM `address`
ORDER BY ISNULL(`company`), `company` ASC, COALESCE(`parent_id`, `address_id`), `parent_id` IS NOT NULL

Which does the job perfeclty

What I'm targeting is the following sorted Output

ID| PARENT_ID | COMPANY | NAME
1 | NULL      | A       | NULL
2 | 1         | A.A     | NULL
3 | 1         | A.B     | NULL
4 | NULL      | B       | NULL
5 | NULL      | C       | NULL
6 | NULL      | D       | NULL
7 | 6         | D.A     | NULL
8 | NULL      | NULL    | A

I'm using Symfony 2 and Doctrine. Currently I use the Doctrine query Builder because the OrderBy should be part of a search I implemented with different aspects (serch by tags, search by different fields "address" ...)

When I try to add "IS NULL" or "COALESCE" to

$qb->add('orderBy', ' >ORDERBY_STATEMENT< ');

Or in any other way to write the order by statement with the query builder

I get the following

[Syntax Error] line 0, col 90: Error: Expected end of string, got 'IS'

I figured out that Doctrine is not vendor specific and therefore can't support all vendor functions.

I read an article about extending Doctrines DQL functions. But there is already an "isNull" function using the Doctrine Expressions which doesnt work inside the OrderBy for me.

Anybody got an Idea how I can achieve the described OrderBy statement using the query builder ?

like image 973
nixoschu Avatar asked Aug 09 '13 14:08

nixoschu


1 Answers

may be this is can help :

$qb = $em->createQueryBuilder();
$qb->select('Entity, COALESCE(Entity.column1, Entity.column2) as columnOrder')
   ->from('Namespace\EntityName', 'Entity')
   ->addOrderBy('columnOrder', 'ASC')
   ->getQuery()
   ->execute();
like image 84
Andi Sholihin Avatar answered Sep 18 '22 16:09

Andi Sholihin