NestJs/TypeORM:如何保存多对多 [英] NestJs/TypeORM: How to save Many to Many

查看:32
本文介绍了NestJs/TypeORM:如何保存多对多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试挽救多对多关系.每个实体本身都运行良好.

I am trying to save a Many to Many relationship. Each entity by itself is working great.

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

Here are the two entity files I am working with:

// 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);

查看本指南 让人觉得我应该能够在我的关系中调用 save() .就我而言 user.locations.save(locations).

Looking at this guide makes it seem like I should be able to call save() on my relationship. In my case user.locations.save(locations).

然而,这会返回一个错误:

However, that is returning an error:

Location[]"类型上不存在属性save".

Property 'save' does not exist on type 'Location[]'.

使用这个SO线程我知道我需要循环遍历位置 ID 的数组并创建我需要保存的实际对象:

Using this S.O thread I know I need to loop through the array of location Id's and create the actual object I need to save:

[{ locationId: location, userId: user.id }]

我需要保存用户,这样我才能得到一个用户 ID.

I need to save the user first so I can get a userId.

如何将我的关系保存到我的 location_users_user 表?感谢您的任何建议!

How can I save my relationship to my location_users_user table? Thank you for any suggestions!

编辑

谢谢@Youba!有关详细信息,请参阅下面的解决方案.希望这会帮助其他人...

Thank you @Youba! See the solution below for more info. Hopefully this will help someone else...

// 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 方法,数据透视表将适当更新.

cascade is false by default. Enabling this will allow you to call the save method and the pivot table will update appropriately.

您还需要引入另一个模块(用户/位置等).感谢 Youba,您可以查看如何实现在这里.

You'll also need to pull in another module (user/locations etc). Thanks to Youba, you can see how to implement that here.

推荐答案

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

What you need to do is to get the locations data and bind it to the new user

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

  

这篇关于NestJs/TypeORM:如何保存多对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆