Roland
Roland

Reputation: 303

Doctrine QueryBuilder order by the amount of 2 fields

I would like to calculate the amount of 2 fields, and ordering the results by. The querybuilder ends like this:

$qb->orderBy('(e.likesCnt + e.additionalLikes)', 'DESC')

and I got this error:

An exception has been thrown during the rendering of a template ("[Syntax Error] line 0, col 264: Error: Expected end of string, got 'e'")

Last try was when:

$qb->select('e, (e.likesCnt + e.additionalLikes) AS totalLikes')
$qb->orderBy('totalLikes', 'DESC')

but it brings an error too

An exception has been thrown during the rendering of a template ("[Semantical Error] line 0, col 290 near 'totalLikes DESC,': Error: 'totalLikes' is not defined.")

Any solutions gratefully accepted :-)

Update: Well, alias is not allowed in the "orderby" statement. Also, if one of your field is null then the amount will be null too, that's cause the semantical error. My solution is:

$qb->orderBy('((e.likesCnt + e.additionalLikes)+0)', 'DESC')

In this case, the ordering will be applicated without semantical error and gets the correct results.

Upvotes: 0

Views: 84

Answers (1)

Imanali Mamadiev
Imanali Mamadiev

Reputation: 2654

The select method is getting parameter as array, for example:

$qb->select('e', '(e.likesCnt + e.additionalLikes) AS totalLikes')
$qb->orderBy('totalLikes', 'DESC')

Upvotes: 1

Related Questions