Creating an Inner Join Query Using TypeORM's QueryBuilder: A Step-by-Step Guide

Hello there! I'm new to TypeORM and haven't had much experience with ORM. I'm finding it a bit challenging to grasp the documentation and examples available online.

My main goal is to utilize the TypeORM QueryBuilder in order to create this specific query:

select first_name, last_name
from users u
inner join company_relations cr
on u.id = cr.id

I appreciate any assistance you can provide!

Answer №1

To enhance your functionality, focus on two key components: your entities and the query.

Here's an example of how your entities could be structured:

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;
}

With these in place, you can execute a query similar to the following:

await this.repository
    .createQueryBuilder('u')
    .select(['u.firstName', 'u.lastName'])
    .innerJoin('m.companyRelations', 'cr')
    .getOne();

For more detailed information, refer to the official documentation here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for linking HTTP requests in Angular 2 depending on the type of response

My attempt to create an api call from a remote server and then, if an error occurs, make another request from my local server is not working as expected. I am encountering errors and need help to determine if my approach is feasible. Here is the code snip ...

How can typescript configurations be imported/exported in a node environment?

I'm encountering difficulties while trying to set up a TypeScript node project and import modules: Below is the structure of my project: /build /src main.ts ...

Changing the selection on multiple input fields in Angular

I am working with two select elements in my form. Based on the selected value from the first select, I am filtering data for the second select. Additionally, I have an option to add the same row of form if desired. My issue is that when I select a value fr ...

The seamless union of Vuestic with Typescript

Seeking advice on integrating Typescript into a Vuestic project as a newcomer to Vue and Vuestic. How can I achieve this successfully? Successfully set up a new project using Vuestic CLI with the following commands: vuestic testproj npm install & ...

Steps to resolve the issue of being unable to destructure property temperatureData from 'undefined' or 'null' in a React application without using a class component

CODE: const { temperatureData } = state; return ( <> <div className="flex flex-row"> {temperatureData.map((item, i) => ( <div className="flex flex-auto rounded justify-center items-center te ...

Tips for dynamically accessing object properties in TypeScript

I've been going through the process of converting existing Node.js projects to TypeScript. As part of this, I am utilizing the http-status package (https://www.npmjs.com/package/http-status) for handling HTTP status codes. While trying to pass varia ...

Is it possible to limit the items in a TypeScript array to only accept shared IDs with items in another array?

I'm creating an object called ColumnAndColumnSettings with an index signature. The goal is to limit the values of columnSettings so that they only allow objects with IDs that are found in columns. type Column = { colId: string, width?: number, s ...

Creating an object property conditionally in a single line: A quick guide

Is there a more efficient way to conditionally create a property on an object without having to repeat the process for every different property? I want to ensure that the property does not exist at all if it has no value, rather than just being null. Thi ...

Set up a personalized React component library with Material-UI integration by installing it as a private NPM package

I have been attempting to install the "Material-UI" library into my own private component library, which is an NPM package built with TypeScript. I have customized some of the MUI components and imported them into another application from my package. Howe ...

Using Javascript to parse SOAP responses

Currently, I am working on a Meteor application that requires data consumption from both REST and SOAP APIs. The SOAP service is accessed using the soap package, which functions properly. However, I am facing challenges with the format of the returned data ...

Ways to display the ping of a game server on your screen

Is there a way to display the game server's ping on the screen like in the example below? this.tfEnter.text = ShowPing + " ms"; Sometimes the code snippets provided in examples may not function properly. Channel List Image: https://i.stack ...

The ultimate guide to loading multiple YAML files simultaneously in JavaScript

A Ruby script was created to split a large YAML file named travel.yaml, which includes a list of country keys and information, into individual files for each country. data = YAML.load(File.read('./src/constants/travel.yaml')) data.fetch('co ...

A programming element that is capable of accessing a data member, but mandates the use of a setter method for modifications

I am unsure whether I need a class or an interface, but my goal is to create an object with a member variable that can be easily accessed like a regular variable. For example: interface LineRange { begin: number; end: number; } However, I want th ...

Ways to add a React Router Link to a Material UI TableRow

When attempting to incorporate a Link component from React Router Dom into my Material UI TableRow, I encountered an issue. <TableRow component={Link as any} to={`/company/${company.id}`} className="clt-row" key={company.id}> The error message I re ...

Conceal a division based on its numerical position

I'm having trouble figuring out how to hide multiple divs based on an index that I receive. The code snippet below hides only the first div with the id "medicalCard", but there could be more than one div with this id. document.getElementById("medical ...

Typeorm encountered an error when attempting to assign the unknown type to an entity

I'm encountering difficulties while using TypeOrm with TypeScript for a specific project. It appears that TypeScript is unable to recognize a type being returned from a TypeORM entity. @Entity({ name: "users", synchronize: false }) export default c ...

Having trouble utilizing the DatePicker component in my react native application

I've encountered an issue while using DatePicker in react native. Whenever I try to use it, an error pops up saying: "render error a date or time must be specified as value prop". Here is the link to my repository: my github repository const [date, se ...

What is the best way to manage tables with a ManyToOne relationship in TypeORM when it comes

I have a scenario where I am working with two entities that have a ManytoOne relationship between them: The entities involved are: PersonalProfile Language Their relationship is defined in the code snippet below: import BaseModel from "@models/Base ...

Tips for adding items to a Form Array in Angular

I am working on a project with dynamic checkboxes that retrieve data from an API. Below is the HTML file: <form [formGroup]="form" (ngSubmit)="submit()"> <label formArrayName="summons" *ngFor="let order of form.controls.summons.controls; let i ...

Create TypeScript declaration files dynamically within the application's memory

Is there a way to programmatically generate declaration files using TypeScript? I know we can use tsc --declaration --emitDeclarationOnly --outFile index.d.ts, but I'm not sure how to do it in code. For example: import ts from 'typescript' c ...