How can I order by NULL in DQL?

后端 未结 6 721
野趣味
野趣味 2021-01-02 20:18

I\'m building an app using Symfony2 framework and using Doctrine ORM. I have a table with airlines for which some IATA codes are missing. I\'m outputting a list, ordered by

6条回答
  •  有刺的猬
    2021-01-02 20:41

    You can use the following trick in DQL to order NULL values last

    $em->createQuery("SELECT c, -c.weight AS HIDDEN inverseWeight FROM Entity\Car c ORDER BY inverseWeight DESC");
    

    The HIDDEN keyword (available since Doctrine 2.2) will result in omitting the inverseWeight field from the result set and thus preventing undesirable mixed results.

    (The sort fields value is inverted therefore the order has to be inverted too, that's why the query uses DESC order, not ASC.)

    Credits belong to this answer.

提交回复
热议问题