让我们定义例如以下实体:
@Entity()
export class Author {
@OneToMany(() => Book, book => book.author)
books = new Collection<Book>(this);
}
@Entity()
export class Book {
@Property()
name: string;
@ManyToOne()
author: Author;
}
const authors = await authorRepository.find({ books: {name: 'Test'} }, {
limit: 10
});
如您所见,我想选择所有具有名称为“ Test”的书的作者,但这将生成以下查询:
select `e0`.* from `author` as `e0`
left join `book` as `e1` on `e0`.`id` = `e1`.`author_id`
where `e1`.`name` = 'Test' limit 10
问题是当我有2个以上的作者并且每个作者都有10多个名为“ Test”的书时,由于limit子句,此查询将仅返回第一位作者。
我不确定这是ORM中的错误还是预期的行为。
一种解决方法是选择没有限制子句的所有行,并像在休眠状态一样在内存中进行分页,但是我不确定大型表将使用多少内存,这可能会阻塞处理它们时在NodeJS中发生事件循环。
答案 0 :(得分:0)
您可以在此处回退到查询构建器以应用group by子句:
const qb = await authorRepository.createQueryBuilder('a');
qb.select('a.*').where({ books: { name: 'Test' } }).limit(10).groupBy('a.id');
const authors = await qb.getResult();
将考虑如何通过EM /存储库API直接支持此用例。