'typeorm: saving an entity with many-to-many relationship ids

Is it possible to save an entity with many-to-many relation ids?

suppose I have following Project Entity with many-to-many relationship to userGroups table.

@Entity()
export class Project extends BaseEntity {
  @Column({ type: 'varchar', length: 255 })
  name: string

  @RelationId((project: Project) => project.userGroups)
  userGroupIds: number[]

  @ManyToMany(type => UserGroup, userGroup => userGroup.projects)
  @JoinTable()
  userGroups: UserGroup[]
}

Since ids of the userGroups table are mapped to userGroupIds property of the Project class via @RelationId decorator, I thought I could save a new Project entity with userGroupIds like this:

let prj = new Project()
prj.name = 'foo'
prj.userGroupIds = [1, 2, 3]
prj.save()

but the above code only creates a project record... (no record is created on project - userGroups many-to-many relation table)



Solution 1:[1]

If you want to add existing entities to a new entity, you can do so as follows (using the same code from the example)

Given:

@Entity()
export class Project extends BaseEntity {
  @Column({ type: 'varchar', length: 255 })
  name: string

  @RelationId((project: Project) => project.userGroups)
  userGroupIds: number[]

  @ManyToMany(type => UserGroup, userGroup => userGroup.projects)
  @JoinTable()
  userGroups: UserGroup[]
}

To add new entries:

idsToAdd = [1,2,3] // Assume these already exist
let prj = new Project()
prj.name = 'foo'
prj.userGroupIds = idsToAdd.map(id => ({...new UserGroup(), id})) // Convert each of the ids into the proper entity.
prj.save() //  Typeorm will ignore the other fields and only update the Ids, as you expect.

An alternative would be to map each id to {id: id}, but typescript is likely to complain about that mapping, since there are probably other fields that are required in the entity/class.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hikash