是否可以保存具有多对多关系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多对多关系表)
答案 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