相关疑难解决方法(0)

NestJs/TypeORM:如何保存多对多

我正在尝试保存多对多关系。每个实体本身都运行良好。

这是我正在使用的两个实体文件:

// 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 数组并创建我需要保存的实际对象: …

typeorm nestjs

5
推荐指数
1
解决办法
4890
查看次数

标签 统计

nestjs ×1

typeorm ×1