gpt4 book ai didi

typescript - NestJS & TypeORM : DTO format in post request

转载 作者:行者123 更新时间:2023-12-04 17:35:25 25 4
gpt4 key购买 nike

我的应用程序中有这些实体。

类别.ts

export class Category {
@PrimaryGeneratedColumn()
Id: number

@Column()
Name: string

@OneToMany(type => SubCategory, subcategoy => subcategoy.Category)
SubCategories: SubCategory[];
}

子类别.ts

export class SubCategory {
@PrimaryGeneratedColumn()
Id: number

@Column()
Name: string

@ManyToOne(type => Category, category => category.SubCategories)
@JoinColumn({name: "CategoryId"})
Category: Category;
}

现在,如果我想添加一个新的子类别,我的 DTO 格式应该是什么样的?我尝试了以下操作,但外键 (CategoryId) 为 NULL。

子类别Dto.ts

export class SubCategoryDto {
Id: number;
Name: string;
CategoryId: number;
}

我理解为什么 CategoryId 列的值在数据库中为空,因为尝试将 CategoryId 转换为 Category,但由于两者的类型不同而失败。我可以执行以下操作,但我觉得这只会使请求数据更大(即使有点)

export class SubCategoryDto {
Id: number;
Name: string;
Category: CategoryDto; //has the properties of Id and Name
}

那么SubCategoryDto的格式应该是怎样的呢?我是否需要通过首先从数据库中获取类别然后创建 SubCategory 实体来将 DTO 转换为实体类?例如:
//request data for new sub-category
{
Name: "Subcategory 1",
CategoryId: 1
}

在服务器端

const newSubcategory    = new SubCategory(); //entity class
newSubcategory.Name = subCategoryDto.Name;
newSubcategory.Category = await this.categoryService.findById(subCategoryDto.CategoryId)
await this.subCategoryService.create(newSubcategory);

但是,如果我这样做会不会是一个额外的数据库调用?处理这种情况的最佳方法是什么?我在互联网上搜索了一整天,找不到与此相关的内容。我想这是一件没有人需要问的简单的事情,但不幸的是我不确定应该如何处理。任何帮助,将不胜感激。

最佳答案

您需要在 SubCategory 实体中添加 CategoryId 属性以允许映射 DTO 和实体:

export class SubCategory {
@PrimaryGeneratedColumn()
Id: number

@Column()
Name: string

@Column()
CategoryId: number

@ManyToOne(type => Category, category => category.SubCategories)
@JoinColumn({name: "CategoryId"})
Category: Category;

}

TypeORM 自动生成该列,但没有“手动”声明,DTO 的字段 CategoryId 试图在 Category 实体中转换并失败。

关于typescript - NestJS & TypeORM : DTO format in post request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56839042/

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