Introduction
A query builder helps you create database queries easily without writing raw SQL. It makes building queries safer and clearer.
A query builder helps you create database queries easily without writing raw SQL. It makes building queries safer and clearer.
const query = dataSource .getRepository(Entity) .createQueryBuilder('alias') .where('alias.field = :value', { value: someValue }) .getMany();
createQueryBuilder on a repository or data source to start building a query.where with parameters to safely add conditions.const users = dataSource .getRepository(User) .createQueryBuilder('user') .where('user.age > :age', { age: 18 }) .getMany();
const user = dataSource .getRepository(User) .createQueryBuilder('user') .where('user.id = :id', { id: 1 }) .getOne();
const count = dataSource .getRepository(User) .createQueryBuilder('user') .where('user.isActive = :active', { active: true }) .getCount();
This service method uses the query builder to get all active users older than a given age.
import { Injectable } from '@nestjs/common'; import { DataSource } from 'typeorm'; import { User } from './user.entity'; @Injectable() export class UserService { constructor(private dataSource: DataSource) {} async getActiveUsersAboveAge(age: number): Promise<User[]> { return this.dataSource .getRepository(User) .createQueryBuilder('user') .where('user.isActive = :active', { active: true }) .andWhere('user.age > :age', { age }) .getMany(); } }
Always use parameters (like :age) to prevent SQL injection.
You can chain multiple where and andWhere calls to add more conditions.
Query builder works well with TypeORM in NestJS for database operations.
Query builder helps build safe and readable database queries.
Use it to fetch, update, or delete data with conditions.
It avoids raw SQL and reduces errors.
QueryBuilder in NestJS with TypeORM?User in NestJS with TypeORM?createQueryBuilder.createQueryBuilder correctly.users?
const users = await this.userRepository
.createQueryBuilder('user')
.where('user.age > :age', { age: 18 })
.getMany();age > 18, so only users older than 18 are selected.getMany() returns an array of matching users, not a single user or error.const user = await this.userRepository
.createQueryBuilder('user')
.where('user.name = :name', { username: 'Alice' })
.getOne();:name but the object key is username, causing mismatch.:name is undefined, causing query error or no results.where and orWhere.where with age and orWhere with role, both with parameters.Pass the test and this pattern moves unknown