使用 typeorm 对多列进行排序

问题描述 投票:0回答:2

在我的应用程序中,我正在使用

MySQL
typeorm
并希望使用多列来执行
orderBy
。我找了很多地方都没有找到解决办法。

示例: 我在表用户和各自的用户实体中有两列

________________________________________
|编号 |名称 |创建日期 |创建时间 |
----------------------------------------------------
| 1 |赛| 2020-12-12 | 12:20:30 | 12:20:30
........................................
| 2 |拉维 | 2020-12-13 | 13:20:30 | 13:20:30
........................................

在这里,我想使用如下所示的

typeorm
来按createdDate和CreateTime进行排序。

CM.getRepository(User)
      .createQueryBuilder('user')
      .select(["name", "id"])
      .orderBy('user.createdDate', 'ASC')
      .AndOrderBy('user.createdTime', 'ASC')

请帮我解决这个问题。

谢谢你...

mysql sql orm sql-order-by typeorm
2个回答
46
投票

来自类型ORM

/**
 * Adds ORDER BY condition in the query builder.
 */
addOrderBy(sort: string, order?: "ASC" | "DESC", nulls?: "NULLS FIRST" | "NULLS LAST"): this;

只需将

AndOrderBy
替换为
addOrderBy
:

CM.getRepository(User)
      .createQueryBuilder('user')
      .select(["name", "id"])
      .orderBy('user.createdDate', 'ASC')
      .addOrderBy('user.createdTime', 'ASC') 

-1
投票

如果您不想使用查询生成器,这里有一个简写版本。

    const users = await User.find({
      where: { userId },
      order: { createdAt: "ASC", createdTime: "ASC" },
     });

它将首先根据创建的第一列进行排序,然后是第二列。列创建时间。

© www.soinside.com 2019 - 2024. All rights reserved.