NestJS TypeORM ManytoMany 如何保存到相关table中的参数?

NestJS TypeORM ManytoMany how to save to a parameter in a related table?

我目前有一个 nestjs 服务 /api/permission 要创建新权限,我会为 REQUEST 发送以下参数:

{"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参数也被保存,在PermissionRoletable中,每个角色都有这样一个条目:

RoleId PermissionId
7 200
8 200
9 200

在我的 permission.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,
        },
    );
}

我的总结Permission.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(
        () => Role,
        (Role: Role) => Role.permissions,
    )
    roles: Role[];
}

我的总结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(
        () => Permission,
        (Permission: Permission) => Permission.roles,
        {
            nullable: false,
            eager: true,
        },
    )
    @JoinTable({
        name: 'PermissionRole',
    })
    permissions: Permission[];

    @ManyToMany(
        () => User,
        (User: User) => User.roles,
    )
    users: User[];

    @ManyToMany(
        () => User,
        (User: User) => User.rolesCanAssign,
    )
    usersCanAssign: User[];
}

您必须在 Permission.entity.ts

中像这样定义多对多
 @ManyToMany(() => Role , (role) => role.id)
  @JoinTable({
    name: 'Permission_Role',
    joinColumn: {
      name: 'permissionId',
      referencedColumnName: 'id'
    },
    inverseJoinColumn: {
      name: 'roleId',
      referencedColumnName: 'id'
    }
  })
  roles: Role[];

并且在permission.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) => {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
 }];