在 TypeORM 中排序嵌套实体时出现问题

Problem ordering nested entities in TypeORM

我有一个名为 Category 的自引用实体。基本上,它只是一个可以包含子文件夹的文件夹,但子文件夹不能包含任何其他文件夹。就那么简单。用户可以通过这种方式移动这些文件夹,从而改变它们之间的相对位置。在 Category 实体上,我有一个名为 position 的道具,当我 return 特定用户的所有类别时,我需要按位置对它们进行排序。也就是说查询应该是这样的:

const categories = await this.categoryRepository.createQueryBuilder('category')
  .where('category.user.id = :userId', { userId })
  .leftJoinAndSelect('category.entries', 'catEntries')
  .leftJoinAndSelect('catEntries.images', 'catImages')
  .leftJoinAndSelect('category.subcategories', 'subs')
  .leftJoinAndSelect('subs.entries', 'subCatEntries')
  .leftJoinAndSelect('subCatEntries.images', 'subCatImages')
  .orderBy('category.position', 'ASC')
  .getMany();

这段代码的问题在于排序不适用于子类别。 因此,我的问题是“我如何编写一个查询,不仅可以对类别进行排序,还可以对子类别进行排序?”。

非常感谢!

尝试添加一个 addOrderBy('subs.SORT', 'ASC'),其中 SORT 是您想要对订阅进行排序的 属性 (position?)

注意 OrderBy()addOrderBy() 之间的区别。前者覆盖之前的,后者允许您添加多个 order by 子句。