【问题标题】:How to paginate results when filtering on left join table column过滤左连接表列时如何对结果进行分页
【发布时间】:2020-04-12 18:11:21
【问题描述】:

让我们定义例如这些实体:

@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”时,由于限制子句,此查询将仅返回第一作者。

我不确定这是 ORM 中的错误还是预期的行为。

解决此问题的一种方法是选择没有限制子句的所有行并像在休眠中一样在内存中进行分页,但我不确定非常大的表将使用多少内存,这可能会阻塞NodeJS 中的事件循环,同时处理它们。

【问题讨论】:

    标签: mikro-orm


    【解决方案1】:

    您可以在此处回退到查询生成器以应用分组子句:

    const qb = await authorRepository.createQueryBuilder('a');
    qb.select('a.*').where({ books: { name: 'Test' } }).limit(10).groupBy('a.id');
    const authors = await qb.getResult();
    

    将考虑如何通过 EM/repository API 直接支持此用例。

    【讨论】:

      猜你喜欢
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-07
      • 1970-01-01
      • 1970-01-01
      • 2019-02-05
      相关资源
      最近更新 更多