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;
}
}
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.
Use TypeORM lazy relations // note entity @ManyToMany(() => Subject, (subject: Subject) => subject. notes) subjects: Promise<Subject[]>; // subject entity @ManyToMany(() => Note, note => note.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With