I need to order data by two columns (when the rows have different values for column number 1, order by it; otherwise, order by column number 2)
I'm using a QueryBuilder
to create the query.
If I call the orderBy
method a second time, it replaces any previously specified orderings.
I can pass two columns as the first parameter:
->orderBy('r.firstColumn, r.secondColumn', 'DESC');
But I cannot pass two ordering directions for the second parameter, so when I execute this query the first column is ordered in an ascending direction and the second one, descending. I would like to use descending for both of them.
Is there a way to do this using QueryBuilder
? Do I need to use DQL?
You have to add the order direction right after the column name:
$qb->orderBy('column1 ASC, column2 DESC');
As you have noted, multiple calls to orderBy
do not stack, but you can make multiple calls to addOrderBy
:
$qb->addOrderBy('column1', 'ASC')
->addOrderBy('column2', 'DESC');