我正在与一些为人们服务的实体合作,因此有些人可能与另一个人有关系。
例如,家庭关系,我的实体是:
@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,存在关系。
有一些方法:
我不知道最好的做法是什么。
解决此问题的一种方法是为 father 和 mother 属性创建一个 单独的 DTO,其中仅包含
id
字段。
这样,您可以在只需要father或mother的id的地方使用这个DTO,并在需要所有属性的地方使用完整的
CreatePersonDto
。
如何为 father 和 mother 属性创建单独的 DTO:
export class PersonRelationDto {
id: number;
}
export class CreatePersonDto {
name: string;
document: string;
// ...
father: PersonRelationDto;
mother: PersonRelationDto;
}
在此示例中,
PersonRelationDto
类仅包含id
字段,这是表示两个人之间的关系所需的唯一字段。 CreatePersonDto
类仍然包含完整的 father 和 mother 属性,但您可以在只需要 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
。
谢谢你。