【发布时间】:2021-03-08 20:07:08
【问题描述】:
我在尝试找出返回新创建的实体及其关系的最佳方式时遇到了麻烦。
独自一人,我拥有的每条路线都在正常工作。这意味着,所有 CRUD 操作都运行良好。如果我对实体执行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'
}
如果我为该实体执行“常规”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 }}
【问题讨论】: