Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine Query Builder, CASE WHEN in ORDER BY

I'm trying to make query with ORDER BY like this in Native SQL

ORDER BY CASE `promotion` WHEN 0 THEN `net_price`
   ELSE `promotion_price`
  END DESC, `net_price` DESC

Something like this

$qb->orderBy('CASE `products.promotion` WHEN 0 THEN `products.net_price`
   ELSE `products.promotion_price`
  END', 'DESC');
$qb->orderBy('products.net_price', 'DESC');

Doesn't work, i'm getting error of unexpected CASE.

So I tried this:

$qb->addSelect('CASE products.promotion WHEN 0 THEN products.net_price ELSE products.promotion_price END price');
$qb->orderBy('products.price', 'DESC');

this time i get

'promotion WHEN': Error: Invalid PathExpression. Must be a StateFieldPathExpression.

In both cases I tried to put it in parenthesis as I found few post saying it helped, unfortunately for me it was just changing error message to unexpected ) in first scenario and

Error: Expected Doctrine\ORM\Query\Lexer::T_FROM, got ')'

for 2nd one.

The question is: Is it possible to use condition in ORDER BY using doctrine query builder?

like image 347
Gustek Avatar asked Oct 26 '25 08:10

Gustek


1 Answers

The CASE construction is vendor specific and not part of Doctrine 2 by default. However you can have a look into the DoctrineExtensions. You can use the IfElse function for your use case.

like image 190
Bram Gerritsen Avatar answered Oct 28 '25 02:10

Bram Gerritsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!