Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a 'case when' in a Doctrine select statement

Tags:

sql

php

doctrine

I have a select query I'd like to perform with Doctrine:

 $resultset = Doctrine_Query::create()
    ->select("t.code, t.description, case when t.id_outcome = 1 then 1 else 0 end as in_progress")
    ->from('LuOutcome t')
    ->orderBy('t.rank')
    ->fetchArray();

And it barfs on the 'case'. The documentation does not mention that it's possible (or not).

I'm wondering if Doctrine lacks the capacity to do so. If so, it's a rather major omission. Does anyone know of a work-around?

like image 625
dland Avatar asked Oct 14 '09 08:10

dland


4 Answers

I just had the same problem and, at first glance, appear to have a workaround. I believe you can 'fool' the Doctrine Select parser into treating it as a sub-query by wrapping it in parenthesis.

Give this a try:

$resultset = Doctrine_Query::create()
->select("t.code, t.description, (case when t.id_outcome = 1 then 1 else 0 end) as in_progress")
->from('LuOutcome t')
->orderBy('t.rank')
->fetchArray();
like image 50
Mike B Avatar answered Nov 16 '22 10:11

Mike B


Case statements do appear to have been added to doctrine at some point: https://github.com/doctrine/orm-documentation/commit/189c729f15d2fafecf92662cad9553c2ec3dccd7#diff-0

like image 40
adavea Avatar answered Nov 16 '22 11:11

adavea


The BNF grammar for the Doctrine Query Language doesn't seem to contain anything related to a CASE construct.

like image 39
Ionuț G. Stan Avatar answered Nov 16 '22 09:11

Ionuț G. Stan


As mentioned by adavea, Doctrine now has added support for CASE expressions. You can do something like

 $resultset = Doctrine_Query::create()
->select("t.code, t.description")
->addSelect("CASE WHEN(t.id_outcome = 1) THEN 1 ELSE 0 END as in_progress")
->from('LuOutcome t')
->orderBy('t.rank')
->fetchArray();

Hope this might help someone, thanks!

like image 2
Azhar Khattak Avatar answered Nov 16 '22 10:11

Azhar Khattak