DEV Community

Md Shahjalal
Md Shahjalal

Posted on

TypeORM | Query Builder

** Hello, Everyone! In this post I am going to discuss an important concept about typeOrm **

Suppose we have two entities like below

1. User Entity:

Assuming a simple User entity with a one-to-one relationship with the Phone entity:

import { Entity, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn } from 'typeorm';
import { Phone } from './Phone';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  email: string;

  @OneToOne(() => Phone, { cascade: true, eager: true }) // Assuming a one-to-one relationship
  @JoinColumn()
  phone: Phone;
}
Enter fullscreen mode Exit fullscreen mode

2. Phone Entity:

import { Entity, PrimaryGeneratedColumn, Column, OneToOne } from 'typeorm';
import { User } from './User';

@Entity()
export class Phone {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  number: string;

  @OneToOne(() => User, user => user.phone)
  user: User;
}
Enter fullscreen mode Exit fullscreen mode

Here's a guide using TypeORM Query Builder for user and phone entries, along with API examples:

1. Import necessary modules:

import { DataSource, EntityManager, QueryBuilder } from 'typeorm';
import { User, Phone } from './entities'; // Import your entity classes
Enter fullscreen mode Exit fullscreen mode

2. Get a reference to the EntityManager:

const entityManager = dataSource.getEntityManager();
Enter fullscreen mode Exit fullscreen mode

3. Insert user:

async function insertUser(user: User) {
  const queryBuilder = entityManager.createQueryBuilder();
  await queryBuilder
    .insert()
    .into(User)
    .values(user)
    .execute();
}
Enter fullscreen mode Exit fullscreen mode

4. Find user:

async function findUser(userId: number) {
  const queryBuilder = entityManager.createQueryBuilder(User);
  const user = await queryBuilder
    .where('user.id = :id', { id: userId })
    .getOne();
  return user;
}
Enter fullscreen mode Exit fullscreen mode

5. Insert phone and join with user:

async function insertPhone(userId: number, phone: Phone) {
  const queryBuilder = entityManager.createQueryBuilder();
  await queryBuilder
    .insert()
    .into(Phone)
    .values(phone)
    .execute();

  // Join the phone with the user (assuming a one-to-one relationship)
  await entityManager.createQueryBuilder()
    .relation(User, 'phone')
    .of(userId)
    .set(phone);
}
Enter fullscreen mode Exit fullscreen mode

6. Find user with phone joined:

async function findUserWithPhone(userId: number) {
  const queryBuilder = entityManager.createQueryBuilder(User);
  const user = await queryBuilder
    .where('user.id = :id', { id: userId })
    .leftJoinAndSelect('user.phone', 'phone')
    .getOne();
  return user;
}
Enter fullscreen mode Exit fullscreen mode

API examples:

Route for inserting a user:

app.post('/users', async (req, res) => {
  const user = req.body;
  await insertUser(user);
  res.status(201).json(user);
});
Enter fullscreen mode Exit fullscreen mode

Route for finding a user with their phone:

app.get('/users/:userId', async (req, res) => {
  const userId = req.params.userId;
  const user = await findUserWithPhone(userId);
  res.json(user);
});
Enter fullscreen mode Exit fullscreen mode

Thank you

Top comments (0)