Pesquisa de site

javascript - Selecionar atributos em repository.find() com relações (TypeORM)


Meu método retorna um objeto bill com todo o objeto User. Eu gostaria que eu retornasse apenas o objeto bill e o User com dois atributos na entidade. Eu uso 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;
    }
  }

Resposta #1

Está um pouco tarde, mas para todos os outros que visitam esta página, pode ser útil, há uma opção disponível no typeorm para que possamos obter o resultado da forma que queremos.

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

Resposta #2

Você pode usar o querybuilder, que é uma das ferramentas mais poderosas do TypeOrm, para fazer isso.

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

Artigos relacionados