假设我有一个像这样的 Typeorm 实体定义:
@Entity()
export class MyEntity {
@PrimaryGeneratedColumn()
id: number;
@Column('varchar', { length: 500 })
name: string;
...
@OneToOne(type => DocumentEntity)
@JoinColumn()
myDoc: DocumentEntity;
@OneToMany(type => DocumentEntity, document => document.myEntity)
@JoinColumn()
otherDocs: DocumentEntity[];
...
}
所以它有几个实体关系,OneToMany/OneToOne
在制作 DTO 时如何解决这个问题?
这里有一个 DTO 示例:
export class CreateMyEntityInputDto {
@IsString()
name: string;
...
@IsOptional()
myDoc: DocumentEntity;
@IsOptional()
otherDocs: DocumentEntity[];
....
}
我不清楚通过 Graphql 的最佳方法
当前的graphql接口(interface):
####################
# @input
####################
input CreateDealInput {
name: String
...
myDoc: DocumentInput
otherDocs: [DocumentInput]
}
如果我设计“传统”RESTful 服务,我将通过单独的端点在数据库中创建文档,等待返回 documentID(s):int
的成功
然后在 myEntity.myDoc/myEntity.otherDocs
中将这些 ID 指定为纯整数
创建新的 myEntity
时的字段(在单独的端点)。
我在这里采取同样的方法吗? 即我是否在 graphql 中的单独查询中创建文档实体,从成功响应中解析出创建的 id,然后在 DTO 定义中指定这些 int 值?
类似于:
@IsOptional()
myDoc: int;
然后,在创建 myEntity 时,通过 id:int 加载那些(现有的)文档实体,然后最终通过 Typeorm 保存?
或者我是否将所有文档字段作为嵌套实体传递到一个大型嵌套 POST graphql 查询中,并使用级联来创建它们?
最佳答案
我自己也遇到了同样的问题。我的解决方案是通过 id 引用嵌套实体。在您的示例中,这将类似于:
export class CreateMyEntityInputDto {
@IsString()
name: string;
...
@IsOptional()
myDocId: string;
@IsOptional()
otherDocIds: string[];
....
}
该解决方案需要多个实体,而不是在一个突变中创建嵌套实体。
关于graphql - NestJS + Typeorm + Graphql : correct design pattern for DTO in nested relations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56487415/