Javascript 按多对多关系上的资源id获取所有嵌套资源

Javascript 按多对多关系上的资源id获取所有嵌套资源,javascript,node.js,typescript,nestjs,typeorm,Javascript,Node.js,Typescript,Nestjs,Typeorm,我想用TypeORM创建一个nestjsapi,它有两个实体,用户和组。一个用户可以加入多个组,一个组可以有多个用户 我为用户创建了这些ORM模型 @Entity('User') export class UserEntity { @PrimaryGeneratedColumn() id: number; // ... @ManyToMany((type: any) => GroupEntity, (group: GroupEntity) => group.use

我想用TypeORM创建一个nestjsapi,它有两个实体,用户。一个用户可以加入多个组,一个组可以有多个用户

我为用户创建了这些ORM模型

@Entity('User')
export class UserEntity {
  @PrimaryGeneratedColumn()
  id: number;

  // ...

  @ManyToMany((type: any) => GroupEntity, (group: GroupEntity) => group.users)
  @JoinTable()
  groups: GroupEntity[];
}
对团体来说呢

@Entity('Group')
export class GroupEntity {
  @PrimaryGeneratedColumn()
  id: number;

  // ...

  @ManyToMany((type: any) => UserEntity, (user: UserEntity) => user.groups)
  @JoinTable()
  users: UserEntity[];
}
调用route
GET localhost:3000/users/1/groups
时,我想返回用户所属的组数组。用户服务执行此操作

const groups: GroupEntity[] = await this.groupsRepository.find({
  where: { userId: 1 },
  relations: ['users'],
});
const users: UserEntity[] = await this.usersRepository.find({
  where: { groupId: 1 },
  relations: ['groups'],
});
调用route
GET localhost:3000/groups/1/users
时,我想返回该组持有的用户数组。组服务执行此操作

const groups: GroupEntity[] = await this.groupsRepository.find({
  where: { userId: 1 },
  relations: ['users'],
});
const users: UserEntity[] = await this.usersRepository.find({
  where: { groupId: 1 },
  relations: ['groups'],
});
不幸的是,两个端点都返回每个嵌套的子资源。似乎忽略了
where
子句。数据库创建两个交叉表

但我希望只有一个交叉表,因为其中一个是多余的,不是吗?。当然,这可能有技术原因。获取子资源的正确方法是什么?

第一个问题 在TypeForm中,当您定义
@manytomy
关系时,您需要在关系的一(拥有)侧使用
@JoinTable

这样,它将只创建一个交叉表

范例

@Entity('User')
export class UserEntity {
  @PrimaryGeneratedColumn()
  id: number;

  // ...

  @ManyToMany((type: any) => GroupEntity, (group: GroupEntity) => group.users)
  @JoinTable()
  groups: GroupEntity[];
}

@Entity('Group')
export class GroupEntity {
  @PrimaryGeneratedColumn()
  id: number;

  // ...

  @ManyToMany((type: any) => UserEntity, (user: UserEntity) => user.groups)
  users: UserEntity[];
}

它将生成三个表users、groups和user\u groups\u group

第二个问题 您可以使用此查询

user = await userRepo.find({
    relations: ['groups'],
    where: { id: user.id }
});
const groups = user.groups
正如您的代码表明您正在使用延迟加载
typeORM
,所以您可以这样做

const user = await userRepo.find({
    where: { id: someId }
});
const groups = await note.groups

谢谢你的回复。因此,如果我没有弄错的话,我将
@JoinTable()
GroupEntity
中删除,然后进行此查询,并对groups服务执行相同的操作?