Search code examples
typeorm

How to apply where-criteria to the same field more than once in TypeORM?


I want to express this query in TypeORM:

select * from user where x > 5 and x < 10

or other variations, like:

select * from user where x > '2020-01-01' and x < '2020-10-10'
select * from user where x >= 5.5 and x <> 10

How do I do it?

userRepo.find({where: {x: MoreThan(5), x: LessThan(10)}})

is obviously not legal.


Solution

  • Basic

    On find-options page there is a between function that lets you just do that

    import {Between} from "typeorm";
    
    const loadedPosts = await connection.getRepository(Post).find({
        likes: Between(1, 10)
    });
    

    So in your case its:

    userRepo.find({where: {x: Between(5,10)}})
    

    Advanced

    If you need more control over the query, as in your appended example, you can use raw

    import {Raw} from "typeorm";
    
    const loadedPosts = await connection.getRepository(Post).find({
        currentDate: Raw(alias =>`${alias} > NOW()`)
    });
    

    Creates:

    SELECT * FROM "post" WHERE "currentDate" > NOW()
    

    Translated to your problem:

    userRepo.find({
        where: {
            x: Raw(alias => `${alias} >= 5.5 and ${alias} <> 10`) 
        }
    })
    

    Custom

    This might become too tedious fast and you might want to resort to the more basic query builder for more control