如何查找类型为id的数组属性在typeorm中包含特定ID的实体

时间:2020-03-02 12:01:13

标签: graphql nestjs typeorm typegraphql

我正在使用nestjs,type-graphql和typeorm创建一个graphql api。我在查找如何执行特定查询时遇到麻烦。假设我有以下实体:

@Entity()
@ObjectType({ description: 'The user model' })
export class User extends BaseEntity {
  @Field(type => ID)
  @PrimaryGeneratedColumn('uuid')
  readonly id: string;

  @Field()
  @Column()
  @IsNotEmpty()
  @IsEmail()
  email: string;

  @Field()
  @IsNotEmpty()
  @Column()
  password: string;

  @Field(type => [Project], { nullable: true })
  @ManyToMany(type => Project)
  @JoinTable()
  projects?: Project[];
}

@Entity()
@ObjectType({ description: 'The project model' })
export class Project extends BaseEntity {
  @Field(type => ID)
  @PrimaryGeneratedColumn('uuid')
  readonly id: string;

  @Field()
  @Column()
  @IsNotEmpty()
  description: string;

  @Field(type => [User], { nullable: true })
  @ManyToMany(type => User)
  @JoinTable()
  participants?: User[];
}

我有以下服务:

import { includes } from 'lodash';

@Injectable()
export class ProjectService {
  constructor(
    @InjectRepository(Project)
    private projectRepository: Repository<Project>,
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {}
  async loadAllForUser(
    userId: string
  ): Promise<Project[]> {
    const projects = await this.projectRepository.find(
      {
          relations: ['participants'],
      },
    );

    return projects.filter(project =>
      includes(
        project.participants.map(participant => participant.id),
        userId,
      ),
    );
  }
}

这将是我的解析器:

@Resolver( of => Project)
export class ProjectResolver {
  constructor(
    private projectService: ProjectService,
    private userService: UserService,
  ) {}
  @Query(returns => [Project])
  @UseGuards(GqlAuthGuard)
  async myProjects(
    @GqlUser() user: User,
  ) {
    return await this.projectService.loadAllForUser(
      user.id,
    );
  }
}

您可以在我的项目服务中看到,我只是使用find方法获取所有项目,然后再使用lodash中的include过滤此列表,以仅过滤出包含用户ID的项目。是否没有办法在项目存储库的find方法中添加某种操作(如“ where”或“ in”),以便我可以直接从那里进行过滤,而不是手动过滤和使用lodash中的include?我什至不知道这是否是我手动过滤方式的正确方法?

亲切的问候,

Gerry

1 个答案:

答案 0 :(得分:0)

尝试使用TypeORM QueryBuilder并进行一些内部联接以筛选不属于所选用户的项目。