'How Do I Build This Inner Join Query With TypeORM's QueryBuilder?
I'm trying to learn TypeORM, I haven't really used an ORM before. I'm having trouble understanding the documentation and other examples online.
I just want to use the TypeORM QueryBuilder to generate the following query.
select first_name, last_name
from users u
inner join company_relations cr
on u.id = cr.id
Thank you for any help!
Solution 1:[1]
You need to work 2 elements, your entities and the query.
For example, your entities should look more or less like this
UserEntity.ts
@Entity('users')
export class UsersEntity {
// other attributes
@Column({ name: 'first_name', type: 'varchar' })
firstName: string;
@Column({ name: 'last_name', type: 'varchar' })
lastName: string;
@OneToMany(
() => CompanyRelationsEntity,
(companyRelationsEntity: CompanyRelationsEntity) => companyRelationsEntity.userId,
)
companyRelations: CompanyRelationEntity[];
}
CompanyRelationEntity.ts
@Entity('company_relations')
export class CompanyRelationEntity {
// Other attributes
@ManyToOne(
() => UsersEntity,
(userEntity: UsersEntity) => usersEntity.companyRelations,
)
@JoinColumn({ name: 'user_id', referencedColumnName: 'id' })
user: UserEntity;
}
Then, you can perform a query similar to this
await this.repository
.createQueryBuilder('u')
.select(['u.firstName', 'u.lastName'])
.innerJoin('m.companyRelations', 'cr')
.getOne();
You can read more about this in its official link
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | normeno |
