在 repository.find() 上选择具有关系的属性(TypeORM)

pro*_*ct5 15 javascript typescript typeorm

我的方法返回一个包含所有用户对象的账单对象。我希望我只返回实体中具有两个属性的账单对象和用户。我使用 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;
    }
  }
Run Code Online (Sandbox Code Playgroud)

The*_*nic 42

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

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

在此输入图像描述


zen*_*eni 13

您可以使用 TypeOrm 最强大的工具之一 querybuilder 来做到这一点。

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();
Run Code Online (Sandbox Code Playgroud)

  • 'execute' 方法返回原始结果,所以也许对你来说最好使用 getMany 来返回一个对象 (2认同)