我是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[];
}
这是到目前为止我的打字机查询:
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();
答案 0 :(得分:0)
您可以在查询中添加.limit(count)。 您的打字机代码将是
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();