【问题标题】:TypeORM relation类型ORM关系
【发布时间】:2020-10-23 23:00:32
【问题描述】:

谁能告诉我为什么我不能在我的createQuerybuilder 中使用relation

let user = await this.conn.getRepository(UserEntity)
                          .createQueryBuilder('user')
                          .relation('orders')
                          .orderBy('user.id', 'ASC') // 'Property 'orderBy' does not exist on type 'RelationQueryBuilder<UserEntuty>.

我的错误是在.orderBy 抛出,但 orderBy 没有问题,因为当我在这个地方放置一个不同的函数时,这个错误仍然存​​在

感谢您的帮助

【问题讨论】:

  • 正如我在文档中看到的关系需要两个参数。 Relation Function
  • @xMayank 我明白了,但是当我将我的实体添加到这个关系中时,我仍然有同样的错误
  • 让我们使用leftJoin()innerJoin() 而不是relation()。会是这样的await this.conn.getRepository(UserEntity).createQueryBuilder('user').innerJoin('user.orders', 'order').orderBy('user.id', 'ASC')

标签: javascript typescript nestjs typeorm


【解决方案1】:

我想这就是你要找的东西:

const users = await this.conn.getRepository(UserEntity)
                              .createQueryBuilder('user')
                              .leftJoinAndSelect('user.orders', 'orders')
                              .orderBy('user.id', 'ASC')
                              .getMany();

在上面的代码中,您将获得一个用户数组。每个用户都有一系列订单。这对你有好处吗?

请参阅文档 here 关于 TypeORM 中的 joins

最好使用 joins 进行 SELECT 操作,而不是 relation 方法。关系文档here

希望对你有帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-29
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    相关资源
    最近更新 更多