I have a many to many relation between two entities users & organizations, as follows:
UserEntity
@ManyToMany(() => OrganizationEntity, organization => organization.users)
@JoinTable({name: 'user_organizations'})
public organizations: OrganizationEntity[];
OrganizationEntity
@ManyToMany(() => UserEntity, user => user.organizations)
public users: UserEntity[];
now when I create it as follows, it works perfectly:
const user = new User({...params})
const organization1 = new Organization({...organizationParams1})
const organization2 = new Organization({...organizationParams2})
user.organizations = [organization1, organization2]
this.usersRepository.save(user)
but later when I need to add a new organization and save it, it gives unique constraint violation for (user_id, organization_id) as it tries to save the old user organizations again
const user = this.usersRepository.find(userId)
const newOrganization= new Organization({...organizationParams})
user.organizations.push(newOrganization)
this.usersRepository.save(user)
I expect it to only save the new organization being added to the user, not all of it related organizations
Note: I need to use .save() to be able to use the updated record in the user subscriber since this method of adding the organization to user doesn’t trigger typeorm afterUpdate
await this.getRepository()
.createQueryBuilder()
.relation(UserEntity, 'organizations')
.of(userId)
.add(organizationId);
what can I do to fix this issue?
Marwan Salah El-Din is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.