You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeORM多对多关系查询:如何获取用户作为管理员的所有组织

TypeORM多对多关联查询指定用户作为管理员的组织解决方案

错误原因

你当前的写法触发了TypeORM的SQL生成逻辑异常:直接在find方法的where条件中嵌套多对多关联属性进行过滤时,TypeORM没有正确识别中间表organization_admins_user的字段,反而错误地去organization主表中查找不存在的关联字段,导致报错。

正确实现方案

推荐使用QueryBuilder写法,兼容性更强,不会出现字段识别错误的问题,代码如下:

@EntityRepository(Organization)
export class OrganizationRepository extends Repository<Organization> {
  private logger = new Logger('OrganizationRepository', true);

  async getUsersOrganizations(user: User) {
    return await this.createQueryBuilder('organization')
      .leftJoinAndSelect('organization.admins', 'admin')
      .where('admin.Userid = :userId', { userId: user.Userid })
      .getMany();
  }
}

如果你使用的是TypeORM 0.3+版本,也可以使用简化的find写法:

async getUsersOrganizations(user: User) {
  return await this.find({
    where: {
      admins: {
        Userid: user.Userid
      }
    }
  });
}

注意:因为你在Organization实体的admins关联上已经配置了eager: true,默认会自动加载关联的管理员数据,不需要额外添加relations配置。

注意事项

  • 查询时关联字段的名称要和实体定义完全一致,你当前User实体的主键名为Userid(注意首字母大写),不要误写为userId等其他拼写
  • 如果不需要返回管理员的完整数据,可以把leftJoinAndSelect替换为leftJoin,减少返回数据体积

内容的提问来源于stack exchange,提问作者Brendan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 21:54:04