【问题标题】:How to find entities where an array property of id's contains a certain id within typeorm如何在typeorm中查找id的数组属性包含某个id的实体
【发布时间】:2020-06-14 17:21:29
【问题描述】:

我正在使用 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 中的包含过滤此列表以仅过滤掉包含用户 ID 的项目。有没有办法在项目存储库的 find 方法中添加某种操作,例如“where”或“in”,以便我可以直接从那里过滤它,而不是手动过滤和使用 lodash 中的包含?我什至不知道我手动过滤的方式是否正确?

亲切的问候,

格里

【问题讨论】:

    标签: graphql nestjs typeorm typegraphql


    【解决方案1】:

    尝试使用 TypeORM QueryBuilder 并进行一些内部连接来过滤不属于选定用户的项目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-23
      • 1970-01-01
      相关资源
      最近更新 更多