[英]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.