【问题标题】:postgresql typeOrm filter manyToMany relationpostgresql typeOrm 过滤多对多关系
【发布时间】:2020-12-03 08:31:28
【问题描述】:

我有 2 个具有多对多关系的实体:

//branch entity
 @ManyToMany(
        (type) => User,
        (e) => e.branches
    )
    users: User[];


//user entity
   @ManyToMany(
        (type) => Branch,
        (e) => e.users,
        {   eager: true,
            cascade: false }
    )
    
    @JoinTable()
    branches: Branch[];


    @IsEnum(Role)
    @Column('text', { default: Role.Client })
    role: Role;

如果用户列表不包含角色为“client”的用户,我想查找分支。

我需要这个,如果我有的话:

[
 Branch {
    id: '98007770-c924-43cd-988c-774492e1e759',
    name: 'poslovnica1',
    users: [ {role:'client'},{role:'superAdmin'} ]
  },
 Branch {
    id: '787007770-c924-43cd-988c-774492e1e759',
    name: 'poslovnica13',
    users: [ {role:'client'},{role:'superAdmin'} ]
  },

  Branch {
    id: '36f5b1ad-6553-4b2f-936b-33fb4ca8e73e',
    name: 'poslovnica2',
    users: [ {role:'superAdmin' }]
  }
]

过滤后我想得到所有分支,如果他们没有用户 角色“客户”。 “超级管理员”或:

[
   Branch {
    id: '36f5b1ad-6553-4b2f-936b-33fb4ca8e73e',
    name: 'poslovnica2',
    users: [ {role:'superAdmin'} ]
  }
]

【问题讨论】:

    标签: typescript postgresql many-to-many nestjs typeorm


    【解决方案1】:

    欢迎来到 StackOverflow !

    你确实很接近它!
    我会尝试使用以下代码(使用 lodash):

    import {values, omit} from 'lodash';
    
    // ....
    
    const notClientRoles = values(omit(Role, Role.Client));
    
    await this.branchRepository
        .createQueryBuilder('b')
        .leftJoin('b.users', 'users')
        .where('users.client IN(:...roles)', { roles: notClientRoles })
        .getMany(); 
    

    详情:

    const notClientRoles = values(omit(Role, Role.Client))
    

    用于从您想要的角色中删除Client 角色(我们使用来自lodashvaluesomit 方法)。我们将它包装在一个变量中,然后在 where 子句中使用它,如下所示:

        .where('users.client IN(:...roles)', { roles: notClientRoles })
    

    如果有帮助请告诉我:)

    【讨论】:

    • 我试试你说的,但我需要别的东西
    【解决方案2】:

    我得到的结果与您尝试使用 lodash 的结果相同,但以另一种方式:

    await branchRepository.find({
                        join: {
                            alias: 'branch',
                            leftJoinAndSelect: {
                                users: 'branch.users'
                            }
                        },
                        where: (qb) => {
                            qb.where('role != :role', { role: 'client' });
                        }
                    });
    

    但我需要按用户过滤分支,而不是用户...感谢尝试!

    【讨论】:

      【解决方案3】:

      我得到了我想要的:

       retVal = await this.branchRepository.find({ relations: ['users'] });
       retVal = retVal.filter((branch: Branch) => {
                      if (!branch.users.some((user) => user.role === Role.Client)) return branch;
                      });
      

      但如果可能的话,我希望改进这一点......

      【讨论】:

        猜你喜欢
        • 2020-10-15
        • 2020-06-29
        • 1970-01-01
        • 2020-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多