Search code examples
typescriptnestjstypeorm

Typeorem parameter not equal to several values


How can I get a query in Typeorm that will get result like this:

SELECT * FROM Users WHERE id <> 3 and id <> 8 and id <> 23;

Thanks


Solution

  • The best way to achieve this correctly is by using the QueryBuilder class in Typeorm. You can read more about it in the link below:

    TypeORM QueryBuilder

    For your specific case you can use the following code snippet to achieve the query that you have mentioned:

    async function getUsers(): Promise<User[]> {
          const userRepository = getConnection().getRepository(User);
          
          const query = userRepository.createQueryBuilder('user')
            .where('user.id <> :id1', { id1: 3 })
            .andWhere('user.id <> :id2', { id2: 8 })
            .andWhere('user.id <> :id3', { id3: 23 });
    
          const users = await query.getMany();
          return users;
    }