【问题标题】:TypeORM find entities where entity.array contains idTypeORM 查找 entity.array 包含 id 的实体
【发布时间】:2022-02-14 18:24:49
【问题描述】:

我正在使用 NestJS + 打字稿。这是我的实体:

@Entity()
export class YearCourse {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @ManyToMany(() => User)
  @JoinTable()
  admins: User[];
}

现在给定user,我想查找给定用户是管理员的所有yearCourse 实体。

原型如下:

async getByUser(user: User): Promise<YearCourse[]> {
  return this.yearCourseRepository.find({where: { admins.contains(user) }})
}

这显然行不通。如何实现这种类型的搜索?

【问题讨论】:

    标签: mysql typescript nestjs typeorm


    【解决方案1】:

    要使用 TypeOrm 编写更高级的 SQL 查询,您可以使用 Query Builder

    考虑到您的 admin idUser 实体中存储为adminId (admin_id),它应该如下所示:

    // query builder name ('year') is completely customisable
    return this.yearCourseRepository.createQueryBuilder('year')
          // load "admins" relation (user entity) and select results as "admins"
          .leftJoinAndSelect('year.admins', 'admins')
          // search where users have the "user.id" as "adminId"
          .where('admins.adminId = :id', { id: user.id })
          // get many results
          .getMany();
    

    我建议您在使用 Query Builder 时直接将其写入您的 存储库文件 以提高整洁度

    【讨论】:

      猜你喜欢
      • 2020-06-14
      • 1970-01-01
      • 2018-06-30
      • 2022-01-06
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多