foreign-keys - TypeORM 官方关系示例不起作用
问题描述
我希望能够保存并返回用户列表及其相关办公室。为此,我根据文档、nestJS、typeORM 和 mongoDB使用官方的一对一关系
用户实体.ts
@OneToOne(() => Office, office => office.user) // specify inverse side as a second parameter
@JoinColumn()
office: Office;
办公实体.ts
@OneToOne(() => User, user => user.office) // specify inverse side as a second parameter
user: User;
保存用户
const officeId = "615c190d9a99101c6ca6cf43"
const officeObject = await this.officesService.findOne(officeId);
user.office = officeObject;
const createdUser = await this.usersService.save(user); // user is an object coming from the request and not an actual model instance
以下方法不返回办公室参考
const users = await this.usersRepository.find({
select: ['id', 'firstName', 'lastName', 'email', 'role', 'office'],
relations: ['office']
});
我究竟做错了什么?
解决方案
TypeOrm 似乎并不容易自动处理关系:https ://github.com/typeorm/typeorm/issues/655
ManyToOne/OneToMany/ManyToMany/OneToOne - 这些装饰器仅在关系数据库中受支持,MongoDB 不支持。Mongodb 是无关系的,所以你不能像在关系数据库中那样轻松地做你想做的事。您应该手动加载所需的数据(组)并将其手动设置为您的实体(用户)。
也许会有这样的功能,但它很复杂,而且我现在正忙于其他任务,所以不会在不久的将来。
推荐阅读
- ruby-on-rails - Rails postgresql left join 使用 has_may order by created_at
- performance - 可以做些什么来降低 UE4Editor 的启动时间?
- php - woocomerce 发送电子邮件付款时执行 URL
- r - 基于 sys.call 在符号 `T` 上使用 `isTRUE()`
- javascript - 返回空数组的函数
- mongodb - 每当我尝试查找最小值和最大值时,我都会得到重复的结果
- reactjs - onClick 返回 SyntheticBaseEvent
- flutter - 继续下载会弄乱文件
- reactjs - 如何在使用上下文 API 和 useReducer 的反应应用程序中测试组件
- autodesk-forge - Autodesk forge 查看器