When you sort on column a descending, it will put all records having a NULL at the bottom, which makes sense. What I want is the following ordering when I’m sorting on attribute a descending:
a
----
NULL
NULL
5
4
3
2
1
I know Oracle has NULLS_FIRST and in MySQL you could use ORDER BY ISNULL(a), but I’m wondering whether there is an elegant way to deal with this using Doctrine2 functionality only? So not using native queries, etc.
Answer with the help of S0pa: I fixed it using the following new function node for Doctrine2:
<?php
namespace MyBundle\General;
use \Doctrine\ORM\Query\Lexer;
class IsnullFunctionNode extends \Doctrine\ORM\Query\AST\Functions\FunctionNode
{
private $isnull;
public function parse(\Doctrine\ORM\Query\Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->isnull = $parser->ArithmeticPrimary();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
{
return 'ISNULL('.$this->isnull->dispatch($sqlWalker).')';
}
}
And connected it in Symfony2 to Doctrine2 like this (app.yml):
doctrine:
orm:
entity_managers:
default:
...
dql:
numeric_functions:
isnull: Diagenda\CommonBundle\General\IsnullFunctionNode
I can’t use these functions in my ORDER BY clause, but by doing a SELECT ISNULL(a) AS n_a I can order on the n_a attribute.
I think the best way is to define your own DQL function, using this tutorial. You will still need to handle different case depending on your DB management system.