Select attributes on repository.find() with relations (TypeORM)

promiseREact5 picture promiseREact5 · Jul 10, 2019 · Viewed 15.3k times · Source

My method returns a a bill object with all of User object. I would like that I return only bill object and User with two attributes in entity. I use 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;
    }
  }

Answer

zenbeni picture zenbeni · Jul 10, 2019

You can use querybuilder which is one of the most powerful tool of TypeOrm, to do so.

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();