簡體   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