gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:36:52 28 4
gpt4 key购买 nike

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

      .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 类上设置 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;

如果您需要选择 TodoEntity 的所有列,那么您将需要在当前左联接之后对 TodoEntity 执行另一个左联接。

干杯! 🍻

关于javascript - 在 Nest.js 应用程序中使用 typeOrm 订购所需的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66722382/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com