首页 > 解决方案 > 如何限制 typeorm 连接查询?

问题描述

我是 typeorm 的新手,也许有人可以解决我的问题。我正在使用 NestJS 和 TypeORM 并有两个表(类别和人才)。我希望找到一种限制 typeorm 连接查询的解决方案。

每个类别可以有很多天赋talent_worked,每个天赋可以有很多类别working_categories。我喜欢找到所有类别并且有受人尊敬的人才,但我希望(限制)只有五个人才。

人才

@Entity('talents')
@Unique(['mobile'])
export class TalentsEntity extends BaseEntity {

    @PrimaryGeneratedColumn('uuid')
    id: string;

    @Column({ nullable: true })
    name: string;
    
    @Column({ unique: true })
    mobile: string;
    
    @Column({ nullable: true })
    email: string;
    
    @Column({ select: false })
    password: string;
    
    @Column({ select: false })
    salt: string;
    
    @Column({ default: false })
    isBlocked: boolean;

    @Column({ default: true })    
    isActive: boolean;

    // relation to categories model
    @ManyToMany(
        type => CategoriesEntity,
        categoriesEntity => categoriesEntity.talent_worked,
        { eager: true },
    )
    @JoinTable({ name: 'talents_working_categories' })
    working_categories: CategoriesEntity[];
}

类别

@Entity('categories')
@Unique(['title'])
export class CategoriesEntity extends BaseEntity {

    @PrimaryGeneratedColumn('uuid')
    id: string;

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

    // relation to talents
    @ManyToMany(
        type => TalentsEntity,
        talentsEntity => talentsEntity.working_categories,
        { eager: false },
    )
    talent_worked: TalentsEntity[];

}

到目前为止,这是我的 typeorm 查询

const query = await this.createQueryBuilder('category');
query.leftJoinAndSelect('category.talent_worked', 'talent');
query.leftJoinAndSelect('talent.working_categories', 'talentCategories');
query.where('talent.isActive = :isActive AND talent.isBlocked = :isBlocked', { isActive: true, isBlocked: false});
if (categoryId) query.andWhere('category.id = :categoryId', { categoryId });
query.select([
    'category.id',
    'category.title',
    'talent.id',
    'talent.name',
    'talentCategories.id',
    'talentCategories.title',
]);
query.orderBy('category.created_at', 'ASC');
query.addOrderBy('talent.created_at', 'ASC');
return await query.getMany();

标签: postgresqlnestjstypeorm

解决方案


您可以将 .limit(count) 添加到查询中。您的 typeorm 代码将是

  const query = await this.createQueryBuilder('category');
    query.leftJoinAndSelect('category.talent_worked', 'talent');
    query.leftJoinAndSelect('talent.working_categories', 'talentCategories');
    query.where('talent.isActive = :isActive AND talent.isBlocked = :isBlocked', { isActive: true, isBlocked: false});
    if (categoryId) query.andWhere('category.id = :categoryId', { categoryId });
    query.select([
        'category.id',
        'category.title',
        'talent.id',
        'talent.name',
        'talentCategories.id',
        'talentCategories.title',
    ]);
    query.orderBy('category.created_at', 'ASC');
    query.addOrderBy('talent.created_at', 'ASC');
    query.limit(5);
    return await query.getMany();

推荐阅读