繁体   English   中英

如何返回新创建的实体及其与 Nest.js/TypeORM 的关系?

[英]How can I return a newly created entity along with it's relationship with Nest.js/TypeORM?

我在试图找出返回新创建的实体及其关系的最佳方法时遇到了麻烦。

独自一人,我拥有的每条路线都在正常工作。 这意味着,所有 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 }}

我认为在.save()实体时无法加载关系。

您必须重新获取实体。 (即使用foo.findOne(..)你可以指定relations属性,然后这将自动加载你的关系)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM