When executing queries in TypeORM, you can use the find or createQueryBuilder methods to construct queries and specify the where clause by passing a condition object, enabling AND and OR conditions. Here are some examples of how to use TypeORM to construct queries with AND and OR conditions.
Using find Method
When using the find method, you can construct AND and OR conditions by passing a more complex object in the where option. Here is an example:
javascriptimport { getConnection } from "typeorm"; const users = await getConnection() .getRepository(User) .find({ where: [ { firstName: "Timber", lastName: "Saw" }, { firstName: "Phantom" } ] });
In this example, the find method returns all users named "Timber" with the last name "Saw", or all users named "Phantom".
Using createQueryBuilder Method
Using createQueryBuilder provides more powerful query construction capabilities, including complex AND and OR logic. Here is an example:
javascriptimport { getConnection } from "typeorm"; const users = await getConnection() .getRepository(User) .createQueryBuilder("user") .where("user.firstName = :firstName", { firstName: "Timber" }) .andWhere("user.lastName = :lastName", { lastName: "Saw" }) .orWhere("user.firstName = :otherFirstName", { otherFirstName: "Phantom" }) .getMany();
In this example, createQueryBuilder is used to find all users named "Timber" with the last name "Saw", or users named "Phantom". The andWhere method adds an AND condition, while the orWhere method adds an OR condition.
Using Brackets to Group Conditions
If you need to combine AND and OR conditions in a query, you can use the Brackets class to create more complex logical combinations:
javascriptimport { getConnection, Brackets } from "typeorm"; const users = await getConnection() .getRepository(User) .createQueryBuilder("user") .where(new Brackets(qb => { qb.where("user.firstName = :firstName", { firstName: "Timber" }) .andWhere("user.lastName = :lastName", { lastName: "Saw" }) })) .orWhere(new Brackets(qb => { qb.where("user.firstName = :otherFirstName", { otherFirstName: "Phantom" }) })) .getMany();
In this example, we use Brackets to group conditions for constructing more complex query logic. First, we have an AND condition combining "Timber" and "Saw"; then, we have a separate OR condition to check for users named "Phantom".
By using the above methods, TypeORM provides flexible ways to construct SQL queries with complex conditions.