我正在尝试保存多对多关系。每个实体本身都运行良好。
这是我正在使用的两个实体文件:
// location.entity
@ManyToMany(type => User, user => user.locations, { eager: true, cascade: true })
@JoinTable()
users: User[];
Run Code Online (Sandbox Code Playgroud)
// user.entity
@ManyToMany(type => Location, location => location.users, { eager: false })
locations: Location[];
Run Code Online (Sandbox Code Playgroud)
这是用户存储库:
// 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);
Run Code Online (Sandbox Code Playgroud)
看了这份指南,我似乎应该能够重新建立save()我的关系。就我而言user.locations.save(locations)。
但是,这会返回一个错误:
类型“Location[]”上不存在属性“save”。
使用这个 SO 线程,我知道我需要循环遍历位置 Id 数组并创建我需要保存的实际对象:
[{ locationId: location, userId: user.id }]
Run Code Online (Sandbox Code Playgroud)
我需要先保存用户,这样我才能获取 userId。
如何将我的关系保存到我的location_users_user表中?感谢您的任何建议!
编辑
谢谢@Youba!请参阅下面的解决方案以获取更多信息。希望这会帮助别人......
// location.entity.ts
...
@ManyToMany(type => User, user => user.locations, { eager: false })
@JoinTable()
users: User[];
Run Code Online (Sandbox Code Playgroud)
// user.entity.ts
...
@ManyToMany(type => Location, location => location.users, { eager: false, cascade: true })
locations: Location[];
Run Code Online (Sandbox Code Playgroud)
cascade默认为 false。启用此功能将允许您调用该save方法,并且数据透视表将适当更新。
您还需要引入另一个模块(用户/位置等)。感谢Youba,您可以在这里了解如何实现它。
您需要做的是获取位置数据并将其绑定到新用户
...
try {
const user = new User(); //user entity
user.uuid = uuidv4();
const locationsData: Location[] = await this.locationRepository.findByIds(locations); // array of location entity
await user.locations = locationsData;
await user.save();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4890 次 |
| 最近记录: |