【发布时间】:2021-04-23 00:55:48
【问题描述】:
我正在尝试保存多对多关系。每个实体本身都运行良好。
这是我正在使用的两个实体文件:
// location.entity
@ManyToMany(type => User, user => user.locations, { eager: true, cascade: true })
@JoinTable()
users: User[];
// user.entity
@ManyToMany(type => Location, location => location.users, { eager: false })
locations: Location[];
这是用户存储库:
// user.repository
...
user.locations = locations; // [1,2,3]
user.uuid = uuidv4();
try {
await user.save();
for (const location of user.locations) {
locationsArray.push({ locationId: location, userId: user.id });
}
await user.locations.save(locationsArray);
看着this guide 让我觉得我应该能够就我的关系打电话给save()。在我的情况下user.locations.save(locations)。
但是,这会返回错误:
“位置[]”类型上不存在属性“保存”。
使用this S.O thread 我知道我需要遍历位置 ID 数组并创建我需要保存的实际对象:
[{ locationId: location, userId: user.id }]
我需要先保存用户,这样我才能得到一个userId。
如何保存与location_users_user 表的关系?感谢您的任何建议!
编辑
谢谢@Youba!有关详细信息,请参阅下面的解决方案。 希望这对其他人有帮助...
// location.entity.ts
...
@ManyToMany(type => User, user => user.locations, { eager: false })
@JoinTable()
users: User[];
// user.entity.ts
...
@ManyToMany(type => Location, location => location.users, { eager: false, cascade: true })
locations: Location[];
cascade 默认为 false。启用此功能将允许您调用 save 方法,并且数据透视表将相应更新。
您还需要引入另一个模块(用户/位置等)。感谢有巴,您可以see how to implement that here.
【问题讨论】: