TypeORM ManyToMany关系高效查询

时间:2020-05-16 13:50:51

标签: postgresql typescript typeorm typeorm-datamapper typeorm-activerecord

import { Entity, Column, BaseEntity, ManyToMany, JoinColumn, PrimaryColumn } from 'typeorm';

@Entity()
export class Permission extends BaseEntity {
    @PrimaryColumn()
    code: string;
}

@Entity()
export class Role extends BaseEntity {
    @PrimaryColumn()
    code: string;

    @ManyToMany(() => Permission, { cascade: false })
    @JoinColumn()
    permission: Permission[];
}

@Entity('users')
export class User extends BaseEntity {
    @PrimaryGeneratedColumn('uuid')
    id: string;

    @Column({ unique: true })
    email: string;

    @ManyToMany(() => Role)
    @JoinColumn()
    roles: Role[];

    @ManyToMany(() => Permission)
    @JoinColumn()
    permissions: Permission[];
}

hasPermission(user: User, code: string): Boolean => {
    // ...
}

我想有效地检查用户是否具有权限。 即John是具有角色['inventoryManager']和权限['listing:delete']的用户。角色inventoryManager具有权限['listing:read', 'listing:update']。因此,John.hasPermission('listing:update')John.hasPermission('listing:delete')都将返回true,而John.hasPermission('listing:create')应该返回false

虽然我可以全选,然后循环遍历是一个解决方案,但我认为效率低下并且选择过度。

1 个答案:

答案 0 :(得分:0)

您是否考虑过使用QueryBuilder? https://github.com/typeorm/typeorm/blob/master/docs/select-query-builder.md#getting-the-generated-query

然后您可以查看查询输出,并尝试不同的联接和过滤策略,并比较其效率。