Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 967
sora Avatar asked Nov 22 '18 08:11

sora


1 Answers

suppose we

@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 persist, i can

let prj = new Project()
prj.name = 'foo'
userGroup a = // create a user group here
prj.userGroupIds.add(a)
prj.save()

after persist, you will see a record in the table project - userGroups 
    |project|     |projet-usergroup|        |usergroup|
    ---------     ------------------        -----------
    |id      |     |idproj|idusergrp|       |idusergrp|

    |1       |     |1     | 1       |        | 1      |

after all you will have something like that
like image 110
Steve Ruben Avatar answered Oct 20 '22 22:10

Steve Ruben