我有两个需要关联的实体,如下所示: 一个项目只能有一种类型(项目类型),但一种类型可以关联多个项目
我有一个项目实体的 DTO,如下所示:
import { ApiProperty } from '@nestjs/swagger';
import { IsNotEmpty, IsNumber, IsOptional, IsString } from 'class-validator';
export class CreateProjectDto {
@ApiProperty({ description: 'project name', example: 'ToDo' })
@IsNotEmpty()
@IsString()
readonly name: string;
@ApiProperty({ description: 'type of project', example: 'Personal' })
@IsOptional()
readonly type: string;
}
我有一个实体:
import {
Column,
CreateDateColumn,
Entity,
JoinTable,
OneToMany,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import { ProjectType } from '../project-type/entities/project-type.entity';
@Entity('projects')
export class Project {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToMany(() => ProjectType, (type) => type.projects)
type: ProjectType;
}
import { Project } from '@/projects/entities/project.entity';
import { Column, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
@Entity('project_type')
export class ProjectType {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@ManyToOne(() => Project, (project) => project.type)
projects: Project[];
}
但我的服务出现错误:
Type 'CreateProjectDto' is missing the following properties from type 'DeepPartial<Project>[]': length, pop, push, concat, and 29 more
如果我将 DTO 从
readonly type: string;
更改为 readonly type: ProjectType;
,此错误就会得到修复
但是当我尝试创建一个项目时,它会要求我提供与类型(id,名称)匹配的属性集,并且在前端我只有一个下拉列表,它呈现来自类型实体/表的选项:
即:
{id:1, name: 'personal'},
{id:2, name: 'business'},
当用户选择该选项时,它只会发送该选项的
id
,而不是整个对象,因此当我尝试保存项目时,它会抛出错误。
我不确定我是否遗漏了某些内容,或者我可能需要向 DTO 添加 type_id 属性,但我刚刚加入后端世界,所以我没有太多经验,甚至我不确定这种方法是否正确。 我刚刚阅读了 NestJS 和 typeORM
的文档这可能是因为您在服务中做了类似的事情
const project = await this.projectRpo.create(createProjectDto);
并且projectDto与您的项目实体定义不匹配,因为项目与类型具有多对一的关系。你必须保持你的 dto 定义不变
@ApiProperty({ description: 'project name', example: 'ToDo' })
@IsNotEmpty()
@IsString()
readonly name: string;
@ApiProperty({ description: 'type of project', example: 'Personal' })
@IsOptional()
readonly type: string;
但是在您的服务中,您首先必须搜索类型实体,该实体对您在 dto 中收到的类型进行数学计算,然后分配给您正在创建的新项目实例,如下所示
const projectType = await this.projectTypeRepo.findOneBy(id: createProjectDto.type)
const newProject = this.projectRepo.create({...createProjectDto, type: projectType})
await this.projectRepo.save(newProject)
您应该了解有关 TypeOrm 的更多信息,以获得更好的说明。 希望对拉扎罗有帮助