选择 repository.find() 上的属性与关系(TypeORM)

新手上路,请多包涵

我的方法返回一个包含所有 User 对象的 bill 对象。我希望我只返回实体中具有两个属性的账单对象和用户。我使用 TypeORM

   /**
   * Returns a bills by account bill
   */
  async getByAccountBill(
    accountBill: string,
    id?: number
  ): Promise<Object | undefined> {
    const userService = new UserService();
    const user = await userService.getById(id);

    const bills = await this.billRepository.find({
      select: ["accountBill"],
      where: {
        accountBill: Like(`${accountBill}%`),
        user: Not(`${user.id}`)
      },
      relations: ["user"] // I get All object Entity (userId, password, login...) I want to only name and surname
    });

    if (bills) {
      return bills;
    } else {
      return undefined;
    }
  }

原文由 promiseREact5 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 420
2 个回答

您可以使用 TypeOrm 最强大的工具之一查询生成器来执行此操作。

 const values = this.billRepository.createQueryBuilder("bill")
    .leftJoinAndSelect("bill.user", "user")
    .where("bill.accountBill LIKE :accountBill", {accountBill})
    .andWhere("user.id = :userId", {userId: user.id})
    .select(["user.name", "user.surname"])
    .execute();

 // NOTE
// .execute() will return raw results.
// To return objects, use .getMany()

原文由 zenbeni 发布,翻译遵循 CC BY-SA 4.0 许可协议

有点晚了,但对于访问此页面的所有其他人可能会有帮助, typeorm 中提供了一个选项,因此我们可以获得我们想要的结果。

 return this.repository.find({
  relations: ['user'],
  loadRelationIds: true,
  where: { ... },
  order: { ... }
});

在此处输入图像描述

原文由 The Mechanic 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题