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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With