使用 Doctrine 按多列排序

2022-01-16 00:00:00 php doctrine sql-order-by

我需要按两列对数据进行排序(当行的第 1 列有不同的值时,按它排序;否则,按第 2 列排序)

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)

我正在使用 QueryBuilder 来创建查询.

I'm using a QueryBuilder to create the query.

如果我再次调用 orderBy 方法,它会替换任何之前指定的排序.

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.

有没有办法使用 QueryBuilder 做到这一点?我需要使用 DQL 吗?

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');

如您所述,多次调用 orderBy 不堆叠,但您可以多次调用 addOrderBy:

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');

相关文章