Kinda Code
Home/Node/TypeORM: AND & OR operators

TypeORM: AND & OR operators

Last updated: January 30, 2024

This concise, straight-to-the-point article gives a few quick examples of using AND and OR operators in TypeORM. No more rambling; let’s get our hands dirty by writing some code.

Creating a sample entity

In the coming examples, we’ll use an entity named Product (with four columns: id, name, price, and color):

// Product entity
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm'

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

    @Column()
    name: string;

    @Column()
    price: number;

    @Column()
    color: string;
}

Using Find Options

AND operator

This code will find all products that satisfy both conditions: the price is less than 100 and the color is blue:

const productRepository = dataSource.getRepository(Product);
const result = await productRepository.find({
        where: {
            price: LessThan(100),
            color: 'blue'
        }
})

OR operator

You can query with the OR operator using square brackets.

This code will find products with prices less than 100 OR whose color is red:

const productRepository = dataSource.getRepository(Product);
const result = await productRepository.find({
        where: [
            {price: LessThan(100)},
            {color: 'red'}
        ]
})

Using Query Builder

AND operator

This code will find all products that satisfy both conditions: the price is less than 200 AND the color is yellow:

const productRepository = dataSource.getRepository(Product);
const result = await productRepository
        .createQueryBuilder('product')
        .where('product.price < :price', { price: 200 })
        .andWhere('product.color = :color', { color: 'yellow' })
        .getMany();

OR operator

This code will find all products that satisfy one of these conditions: the price is less than 200 OR the color is yellow:

const productRepository = dataSource.getRepository(Product);
const result = await productRepository
        .createQueryBuilder('product')
        .where('product.price < :price', { price: 100 })
        .orWhere('product.color = :color', { color: 'yellow' })
        .getMany();

Conclusion

We’ve walked through some examples about querying data with AND and OR operators. This knowledge is very important for backend and mobile developers who want to manipulate databases with TypeORM. If you’d like to explore more new and interesting things about TypeORM and other databases’ relevant stuff, take a look at the following articles:

You can also check out our database topic page for the latest tutorials and examples.

Related Articles