繁体   English   中英

在 Nest.js 应用程序中使用 typeOrm 订购所需的集合

[英]Order required collection with typeOrm in the Nest.js application

我有两个小实体 TodoEntity 和 CategoryEntity。 它创建了我期望在数据库中的表。 我使用 Postgres。 我需要从按实际日期排序的数据库类别中获取 select 。 我可以使用 QueryBuilder select 所有类别。 但问题是我不需要重复类别。 如何使它们与众不同?

      .createQueryBuilder('todo')
      .select('category')
      .innerJoinAndSelect('todo.category', 'category')
      .orderBy('todo.actualTime', 'ASC')
      .getRawMany();
@Entity({ name: 'todo_entity' })
class TodoEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ name: 'name' })
  name: string;

  @Column({ name: 'description' })
  description: string;

  @Column({ name: 'actual_time', type: 'timestamp' })
  actualTime: Date;

  @ManyToOne(() => CategoryEntity, (categoryEntity) => categoryEntity.id, {
    cascade: true,
  })
  category: CategoryEntity;
}


@Entity({ name: 'category_entity' })
class CategoryEntity {
  @PrimaryGeneratedColumn({ name: 'id' })
  id: number;

  @Column({ name: 'title' })
  @Index({ unique: true })
  title: string;
}


我猜您需要按链接的待办事项实体的最新actual_time时间对类别进行排序。

首先,您需要在CategoryEntity class 上设置category_entitytodo_entity的关系。

@Entity({ name: 'category_entity' })
class CategoryEntity {
  @PrimaryGeneratedColumn({ name: 'id' })
  id: number;

  @Column({ name: 'title' })
  @Index({ unique: true })
  title: string;

  @OneToMany(type => TodoEntity, (todos) => todos.category)
  todos: TodoEntity[];
}

然后您可以使用类别存储库中的查询构建器来构建查询,如下所示,

.createQueryBuilder('category')
.leftJoinAndSelect(
  (qb) => qb.from(TodoEntity, 'todo')
    .select('MAX("actual_time")', 'actual_time')
    .addSelect('"categoryId"', 'category_id')
    // Add the columns you want from `TodoEntity`
    .addSelect('description')
    .groupBy('category_id'),
  'last_todo',
  'last_todo.category_id = category.id',
)
// Remove the following line if you need all the columns or update it based on the columns you need
.select(['category_entity.id', 'category_entity.title', 'last_todo.actual_time', 'last_todo.description'])
.orderBy('last_todo.actual_time', 'DESC')
.getRawMany();

如果您想知道categoryId是如何出现在查询中的,它是 typeorm 为todo_entity表自动生成的列,因为我们指定了外键关系。

这应该生成以下 Postgres 查询,

SELECT category_entity.id AS category_entity_id, category_entity.title AS "category_entity_title", last_todo.actual_time, last_todo.description
FROM "category_entity" "category"
LEFT JOIN (
    SELECT MAX("actual_time") AS "actual_time", "categoryId" AS "category_id", "description"
    FROM "todo_entity" "todo"
    GROUP BY category_id
) last_todo
ON last_todo.category_id = category.id
ORDER BY last_todo.actual_time DESC;

如果您需要 select TodoEntity的所有列,那么您需要在当前左连接之后对TodoEntity进行另一个左连接。

干杯!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM