【问题标题】:NestJs/TypeORM: How to save Many to ManyNestJs/TypeORM:如何保存多对多
【发布时间】: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.

【问题讨论】:

    标签: nestjs typeorm


    【解决方案1】:

    您需要做的是获取位置数据并将其绑定到新用户

    ...
      
    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();
        }
    
      
    

    【讨论】:

    • 非常感谢both suggestions 我将更新我的问题以希望对其他人有所帮助。您的建议帮了大忙!
    猜你喜欢
    • 2020-08-29
    • 2020-09-01
    • 2021-10-18
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 2021-08-09
    • 2021-06-27
    • 2020-09-03
    相关资源
    最近更新 更多