How can I update/set different relationship entities (or IDs) for my OneToMany relationship? The entities are these:
@Entity()
export class Role extends BaseEntity {
@PrimaryGeneratedColumn('uuid')
id: string
@Column()
name: string
@OneToMany(type => RolePermission, entity => entity.role, {cascade: true})
permissions: RolePermission[]
}
@Entity('role_permission')
export class RolePermission extends BaseEntity {
@PrimaryGeneratedColumn("uuid")
id: string
@Column()
permission: string
@ManyToOne(type => Role, entity => entity.permissions)
role: Role
}
I am trying to update the role's permissions but with no luck. I have tried this:
const role = await Role.findOneByOrFail({id})
await role.save({
data: {
name: form.name,
permissions: form.permissions.map(permission => RolePermission.create({permission}))
},
})
But it doesn't set the new related entities in the table. I can still see the old relationships
I have also tried this:
const role = await Role.findOneByOrFail({id})
await Role.update({id},{
name: form.name,
permissions: form.permissions.map(permission => RolePermission.create({permission}))
})
But I get this error for this one: Cannot query across one-to-many for property permissions
I have also tried this:
const role = await Role.findOneByOrFail({id})
role.name = form.name
role.permissions = form.permissions.map(permission => RolePermission.create({permission, role}))
await role.save()
But I get QueryFailedError: ER_BAD_NULL_ERROR: Column 'role_id' cannot be null EVEN if I specify the role when creating a RolePermission
Also, tried this:
await DB.createQueryBuilder().relation(Role, "permissions").of(roleId).add(permissionsIds)
But this one doesn't do anything. The table still has the old relationships
Any other solutions to this?