【问题标题】:How can I return a newly created entity along with it's relationship with Nest.js/TypeORM?如何返回新创建的实体及其与 Nest.js/TypeORM 的关系?
【发布时间】: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 }}

【问题讨论】:

    标签: nestjs typeorm


    【解决方案1】:

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

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

    【讨论】:

    • 我刚回到这个。非常感谢您的建议!我已经更新了我的问题以显示我的结果。有很多次我错过了内置/明显的方式。
    猜你喜欢
    • 2021-11-11
    • 2020-01-01
    • 2022-11-13
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多