问题
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[];
Here is the user repository:
// 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);
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:
Property 'save' does not exist on type 'Location[]'.
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 }]
I need to save the user first so I can get a userId.
How can I save my relationship to my location_users_user
table? Thank you for any suggestions!
EDIT
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
is false by default. Enabling this will allow you to call the save
method and the pivot table will update appropriately.
You'll also need to pull in another module (user/locations etc). Thanks to Youba, you can see how to implement that here.
回答1:
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();
}
来源:https://stackoverflow.com/questions/65779400/nestjs-typeorm-how-to-save-many-to-many