#node.js #typescript #nestjs #typeorm
Вопрос:
В настоящее время у меня есть служба /api/permission
nestjs, Чтобы создать новое разрешение, я отправляю следующие параметры для ЗАПРОСА:
{"Id":"","EsName":"rxe2x","EnName":"rxi2x","Name":"rxclv2x","Type":"64","Role":"7,8,9"}
И РЕАКЦИЯ такая
{"status":201,"message":"Permission has been saved successfully.","permission":{"Id":"200","EsName":"rxe2x","EnName":"rxi2x","Name":"rxclv2x","Type":"64","Role":"7,8,9"}}
Я хочу Role
, чтобы параметр также был сохранен в PermissionRole
таблице для каждой роли с такой записью:
Ролевая игра | РазрешениеId |
---|---|
7 | 200 |
8 | 200 |
9 | 200 |
с моего разрешения.service.ts
async createPermission(permission: CreatePermissionDto) { const exist = await this.permissionRepository.findOne({ where: { Name: permission.Name }, }); if (exist) throw new ConflictException( 'The permission already exists.', HttpStatus.CONFLICT.toString(), ); const newPermission = await this.permissionRepository.save(permission); return Object.assign( {}, { status: HttpStatus.CREATED, message: 'Permission has been saved successfully.', permission: newPermission, }, ); }
краткое описание моего разрешения.entity.ts
import { Role } from './Role.entity'; @Entity('Permission', { schema: 'dbo' }) export class Permission extends BaseEntity { @PrimaryGeneratedColumn({ type: 'int', name: 'Id', }) Id: number; @Column('varchar', { nullable: false, name: 'Name', }) Name: string; @Column('int', { nullable: false, name: 'Type', }) Type: number; @Column('varchar', { nullable: false, name: 'EnName', }) EnName: string; @Column('varchar', { nullable: false, name: 'EsName', }) EsName: string; @ManyToMany( () =gt; Role, (Role: Role) =gt; Role.permissions, ) roles: Role[]; }
summary of my Role.entity.ts
import { Permission } from './Permission.entity'; import { User } from './User.entity'; @Entity('Role', { schema: 'dbo' }) export class Role extends BaseEntity { @PrimaryGeneratedColumn({ type: 'int', name: 'Id', }) Id: number; @Column('varchar', { nullable: false, length: 50, name: 'Name', }) Name: string; @Column('varchar', { nullable: true, length: 100, name: 'AccessLevel', }) AccessLevel: string; @Column('bigint', { nullable: true, name: 'VALAccount', }) VALAccount: string; @Column('bit', { name: 'CanModified', default: '1', }) CanModified: string; @ManyToMany( () =gt; Permission, (Permission: Permission) =gt; Permission.roles, { nullable: false, eager: true, }, ) @JoinTable({ name: 'PermissionRole', }) permissions: Permission[]; @ManyToMany( () =gt; User, (User: User) =gt; User.roles, ) users: User[]; @ManyToMany( () =gt; User, (User: User) =gt; User.rolesCanAssign, ) usersCanAssign: User[]; }
Ответ №1:
Вы должны определить много ко многим, как это, в Permission.entity.ts
@ManyToMany(() =gt; Role , (role) =gt; role.id) @JoinTable({ name: 'Permission_Role', joinColumn: { name: 'permissionId', referencedColumnName: 'id' }, inverseJoinColumn: { name: 'roleId', referencedColumnName: 'id' } }) roles: Role[];
И в разрешении.service.ts
async createPermission(permission: CreatePermissionDto) { const exist = await this.permissionRepository.findOne({ where: { Name: permission.Name }, }); if (exist) throw new ConflictException( 'The permission already exists.', HttpStatus.CONFLICT.toString(), ); const newPermissionDao = this.permissionRepository.create(permission); newPermissionDao.roles = permission.roles.map((role) =gt; {roleId: role, permissionId: newPermissionDao.id} ); const newPermission = await this.permissionRepository.save(newPermissionDao); return Object.assign( {}, { status: HttpStatus.CREATED, message: 'Permission has been saved successfully.', permission: newPermission, }, ); }
В принципе, вам нужно создать массив объектов для отношения «многие ко многим», как показано ниже:
permission.roles = [{ roleId: 1, permissionId: 1 }, { roleId: 2, permissionId: 1 }];