TypeOrm: And with OR condition

37 Views Asked by At

I am working with TypeORM in a Node.js application and trying to implement a user list function. The goal is to retrieve users based on certain query parameters, including a search term. The desired SQL query involves filtering users with a specific name ('user18') and matching the search term against both the 'name' and 'email' fields using the LIKE operator. I'm having difficulty achieving this using TypeORM, and I'm seeking assistance in modifying my getUsers function to generate the correct SQL query.

Below is the sql query, Unable to get result in typeorm can you please help me,

SELECT *
FROM "users"
WHERE name = 'user18'
  AND (name like '%[email protected]%' OR email like '%[email protected]%')

This is my user list function:

 async getUsers(@Query() queryParams: any): Promise<{ data: user[]; total: number }> {
        let { page = 1, limit = 10, search = '', sort_by = 'id', sort_order = 'desc' } = queryParams;

        const options: FindManyOptions<user> = {
            order: { [sort_by]: sort_order },
            take: limit,
            skip: page ? (page - 1) * limit : 0,
        };

        const [data, total] = await this.usersRepository.findAndCount(options);

        return { data, total };
    }

I have already implemented the basic functionality, but I am facing challenges in correctly incorporating the desired SQL query conditions into the TypeORM options. Despite my attempts, the generated SQL query does not match my expectations.

I am seeking guidance on how to modify my getUsers function to correctly generate the SQL query with the specified conditions, ensuring it filters users with the name 'user18' and matches the search term against both the 'name' and 'email' fields using the LIKE operator.

0

There are 0 best solutions below