如何在Nest.js中以多个@ManyToMany获取数据

时间:2020-03-18 12:23:54

标签: nestjs typeorm

我在两个实体之间有一个ManyToMany关系,我不知道如何从联接表“ device_users_user”中获取数据

@Entity()
export class Device{

  @PrimaryColumn()
  Name:string;


  @Column({ nullable: true})
  Port:number;

  @Column({ nullable: true})
  IPadress:string;

  @Column({ nullable: true})
  Location:string;

  @ManyToMany(type => User)
    @JoinTable()
    users: User[];

  }
@Entity()
export class User{

  @PrimaryColumn()
  Id:number;
  @Column({ nullable: true})
  Departement:string;
  @Column({ nullable: true})
  FirstName:string;
  @Column({ nullable: true})
  LastName:string;
  @Column({ nullable: true})
  CardNumber:string;
  @Column({ nullable: true})
  MobilePhone:string;

}

1 个答案:

答案 0 :(得分:0)

您不能使用TypeORM API来直接查询联接表(除非您尝试执行原始查询,但是我认为这不是您想要实现的...而且我也不建议这样做,因为它是表名可能会更改...)。

但是,当您使用@ManyToMany声明关系时,可以使用查询生成器加载users的{​​{1}},例如:

devices

documentation of TypeORM提供了更多示例,例如:

  const devicesWithUsers = await deviceRepository.createQueryBuilder('device')
    .leftJoin('device.users', 'user')
    .where(/* whatever you need */)
    .getMany();

其结果可能是:

  const user = await createQueryBuilder("user")
    .leftJoinAndSelect("user.photos", "photo")
    .where("user.name = :name", { name: "Timber" })
    .getOne();