typeorm:保存具有多对多关系ID的实体

时间:2018-11-22 08:31:17

标签: typescript typeorm

是否可以保存具有多对多关系ID的实体?

假设我跟随Project实体与userGroups表具有多对多关系。

@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[]
}

由于userGroups表的ID通过userGroupIds装饰器映射到Project类的@RelationId属性,所以我认为我可以使用如下userGroupIds保存一个新的Project实体:

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

但是上面的代码仅创建一个项目记录...(在项目上未创建任何记录-userGroups多对多关系表)

1 个答案:

答案 0 :(得分:2)

假设我们

@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[]
}

要坚持下去,我可以

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