NestJs - 带有子实体的 DTO

问题描述 投票:0回答:1

我正在与一些为人们服务的实体合作,因此有些人可能与另一个人有关系。

例如,家庭关系,我的实体是:

@Entity()
export class Person {
  @Column({ length: 100 })
  name: string;

  @Column({ length: 20 })
  document: string;

... 
and many other properties
...

  @ManyToOne(() => Person, { nullable: true })
  @JoinColumn({
    name: 'father_id',
    foreignKeyConstraintName: 'fk_person_father',
  })
  father: Person;

  @ManyToOne(() => Person, { nullable: true })
  @JoinColumn({
    name: 'mother_id',
    foreignKeyConstraintName: 'fk_person_mother',
  })
  father: Person;

对于DTO,我就是这样使用的

export class CreatePersonDto {
  name: string;
  document: string;
...
  father: Person;
  mother: Person;
}

问题是,在我使用这个 DTO 的每个地方,我都需要提供所有父亲和母亲的属性,例如姓名和文档,但我只需要它的 id,存在关系。

有一些方法:

  1. 所有的 person 属性都可以为空。 (名称?:字符串,文档?字符串...)
  2. 创建一个“getPersonDTO”,其中除 id 之外的所有属性均可为空。
  3. 然后将 mother 和father 属性更改为 number。

我不知道最好的做法是什么。

node.js nestjs entity dto
1个回答
0
投票

解决此问题的一种方法是为 fathermother 属性创建一个 单独的 DTO,其中仅包含

id
字段。

这样,您可以在只需要fathermotherid的地方使用这个DTO,并在需要所有属性的地方使用完整的

CreatePersonDto

如何为 fathermother 属性创建单独的 DTO

export class PersonRelationDto {
  id: number;
}

export class CreatePersonDto {
  name: string;
  document: string;
  // ...
  father: PersonRelationDto;
  mother: PersonRelationDto;
}

在此示例中,

PersonRelationDto
类仅包含
id
字段,这是表示两个人之间的关系所需的唯一字段。
CreatePersonDto
类仍然包含完整的 fathermother 属性,但您可以在只需要
PersonRelationDto
的地方使用
id
类。

如果你想创建一个带有父亲母亲新人,你可以使用完整的

CreatePersonDto

const createPersonDto: CreatePersonDto = {
  name: 'John Doe',
  document: '123456789',
  father: {
    id: 1,
    name: 'John Doe Sr.',
    document: '987654321',
    // ...
  },
  mother: {
    id: 2,
    name: 'Jane Doe',
    document: '567890123',
    // ...
  },
  // ...
};

如果您只需要

父亲
母亲id,则可以使用
PersonRelationDto

const fatherDto: PersonRelationDto = {
  id: 1,
};

const motherDto: PersonRelationDto = {
  id: 2,
};

此方法允许您在需要所有属性时使用完整的

CreatePersonDto
,在仅需要
PersonRelationDto
时使用
id

谢谢你。

© www.soinside.com 2019 - 2024. All rights reserved.