IFNULL in Symfony2 Doctrine query builder
Asked Answered
A

3

3

How is the IFNULL of SQL implemented in Symfony2 Doctrine Query Builder? Let's say I have this query:

select * from ticket order by IFNULL(modified_date, '2000-01-01') DESC, created_date DESC

I have this DQL:

$this->qb->select("t, c.name")
         ->from("Ticket", "t");
$this->qb->orderBy("t.modifiedDate", "DESC");
$this->qb->addOrderBy("t.createdDate", "DESC");

Now how to add the IFNULL part?

Attorney answered 1/2, 2012 at 16:27 Comment(1)
I have the same problem on my symfony2 projectChoe
A
2

Ok, done some research and found that there is no such implementation.

Googled a little more, and got that this kind of missing features can be added to Doctrine as own functions.

Found this extension on GitHub I think this will work. But wonder if ther would be any problems or conflicts with Doctrine versions...

Attorney answered 2/2, 2012 at 9:52 Comment(1)
Link does not existEducatory
V
1

This is the valid link with the DQL Extension

Edit with the solution explained:

  1. Create the following directory under your project src path: /src/DoctrineExtensions/Query/Mysql

  2. Put there the DQL Extension file (IfNull.php in this case)

  3. Edit your src/config/packages/doctrine.yaml and insert this new lines:

doctrine:
    ...
    orm:
        ...
        dql:
            numeric_functions:
                IFNULL: App\DoctrineExtensions\Query\Mysql\IfNull

  1. In your entity repository you can call this function like this:
$qb = $this->createQueryBuilder('tl')
           ->andWhere('IFNULL(tl.app,0) = 1');
Vincennes answered 18/8, 2021 at 6:48 Comment(0)
S
1

Depending on your usecase you may be able to use the builtin "COALESCE" expression instead of installing the "IFNULL" extension.

The usage then is basically the same as with the IFNULL expression. Just replace IFNULL with COALESCE in the example in https://mcmap.net/q/821895/-ifnull-in-symfony2-doctrine-query-builder.

Note: COALESCE might behave slightly different than IFNULL depending on your database. https://mcmap.net/q/225065/-what-is-the-difference-between-ifnull-and-coalesce-in-mysql contains some great explanations.

List of builtin case-expressions: https://www.doctrine-project.org/projects/doctrine-orm/en/2.13/reference/dql-doctrine-query-language.html#case-expressions

Skiagraph answered 12/10, 2022 at 9:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.