Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
    }
  }
like image 905
promiseREact5 Avatar asked Jul 10 '19 06:07

promiseREact5


People also ask

How do you use relations in TypeORM?

Relations are used to refer the relationship between table in database. In general, a relationship exists between two tables when one of them has a foreign key that references the primary key of the other table. This feature makes relational database more powerful and efficiently store information.

How get data from many to many relationship in TypeORM?

Use TypeORM lazy relations // note entity @ManyToMany(() => Subject, (subject: Subject) => subject. notes) subjects: Promise<Subject[]>; // subject entity @ManyToMany(() => Note, note => note.

How do you change the relationship in TypeORM?

Relation optionscascade: boolean | ("insert" | "update")[] - If set to true, the related object will be inserted and updated in the database. You can also specify an array of cascade options. onDelete: "RESTRICT"|"CASCADE"|"SET NULL" - specifies how foreign key should behave when referenced object is deleted.


1 Answers

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();
// NOTE
// .execute() will return raw results.
// To return objects, use .getMany()
like image 89
zenbeni Avatar answered Sep 19 '22 17:09

zenbeni