Nestjs 如何返回新创建的实体及其';s与Nest.js/TypeORM的关系?
我很难找到返回新创建的实体及其关系的最佳方法 独自一人,我的每一条路线都运转正常。也就是说,所有积垢操作都非常有效。如果我对实体执行Nestjs 如何返回新创建的实体及其';s与Nest.js/TypeORM的关系?,nestjs,typeorm,Nestjs,Typeorm,我很难找到返回新创建的实体及其关系的最佳方法 独自一人,我的每一条路线都运转正常。也就是说,所有积垢操作都非常有效。如果我对实体执行GET,我也会按预期恢复关系 我遇到的问题是,当一个新实体被创建时——我返回那个实体。例如: const foo = this.create(); foo.relationshipId = relationshipId; foo.bar = bar; foo.baz = baz; foo.uuid = uuidv4(); try { await foo.
GET
,我也会按预期恢复关系
我遇到的问题是,当一个新实体被创建时——我返回那个实体。例如:
const foo = this.create();
foo.relationshipId = relationshipId;
foo.bar = bar;
foo.baz = baz;
foo.uuid = uuidv4();
try {
await foo.save();
} catch (error) {
// this.logger.error(`Failed to create the foo: ${error.stack}`);
throw new InternalServerErrorException();
}
return foo;
如果我记录foo
是什么,我会得到如下结果:
foo: {
relationshipId: 1,
bar: 'example',
baz: 'example',
uuid: '123-asdf-example'
}
foo: {
relationshipId: 1,
related: {
some: 'property',
another: 'example',
},
bar: 'example',
baz: 'example',
uuid: '123-asdf-example'
}
我需要的是还包括实际相关的模型/实体。大概是这样的:
foo: {
relationshipId: 1,
bar: 'example',
baz: 'example',
uuid: '123-asdf-example'
}
foo: {
relationshipId: 1,
related: {
some: 'property',
another: 'example',
},
bar: 'example',
baz: 'example',
uuid: '123-asdf-example'
}
如果我对该实体执行“常规”GET
,我会将相关实体连同它一起取回(与上面的示例完全相同)。只有在create
方法中,我才不会返回关系
如何将新创建的实体与关系一起返回?我是否需要对新实体执行GET
?有更好的方法吗
谢谢你的建议
更新/解决方案
这就是最终对我有用的东西(也完全符合@Schutt的建议)。这是我的foo.repository.ts
文件:
...
const foo = this.create();
foo.bar = bar;
foo.uuid = uuidv4();
try {
await foo.save();
} catch (error) {
// this.logger.error(`Failed to create the foo: ${error.stack}`);
throw new InternalServerErrorException();
}
return await this.findOne({
where: { id: foo.id },
relations: ['related'],
});
我现在得到新创建的实体以及相关的实体。
在我的前端,我现在可以显示如下内容:
{{ foo.relation.name }}
我认为在您
.save()
您的实体时无法加载关系
您必须重新获取实体。(即,使用
foo.findOne(..)
可以在那里指定关系
属性,然后将自动加载您的关系)我认为在您.save()
实体时无法加载关系
您必须重新获取实体。(即,使用
foo.findOne(..)
可以在那里指定关系
属性,然后将自动加载您的关系)我刚刚回到这里。非常感谢你的建议!我已经更新了我的问题,以显示我最终得到了什么。有很多次我错过了内置/明显的方式。太棒了!谢谢你的反馈,我刚回到这里。非常感谢你的建议!我已经更新了我的问题,以显示我最终得到了什么。有很多次我错过了内置/明显的方式。太棒了!谢谢你的反馈