• 添加WHERE表达式

    添加WHERE表达式

    添加 WHERE 表达式就像:

    1. createQueryBuilder("user").where("user.name = :name", { name: "Timber" });

    将会生成以下 SQL 语句:

    1. SELECT ... FROM users user WHERE user.name = 'Timber'

    你可以将 AND 添加到现有的 WHERE 表达式中:

    1. createQueryBuilder("user")
    2. .where("user.firstName = :firstName", { firstName: "Timber" })
    3. .andWhere("user.lastName = :lastName", { lastName: "Saw" });

    将会生成以下 SQL 语句:

    1. SELECT ... FROM users user WHERE user.firstName = 'Timber' AND user.lastName = 'Saw'

    你也可以添加 OR 添加到现有的 WHERE 表达式中:

    1. createQueryBuilder("user")
    2. .where("user.firstName = :firstName", { firstName: "Timber" })
    3. .orWhere("user.lastName = :lastName", { lastName: "Saw" });

    将会生成以下 SQL 语句:

    1. SELECT ... FROM users user WHERE user.firstName = 'Timber' OR user.lastName = 'Saw'

    你可以使用Brackets将复杂的WHERE表达式添加到现有的WHERE中:

    1. createQueryBuilder("user")
    2. .where("user.registered = :registered", { registered: true })
    3. .andWhere(new Brackets(qb => {
    4. qb.where("user.firstName = :firstName", { firstName: "Timber" })
    5. .orWhere("user.lastName = :lastName", { lastName: "Saw" })

    将会生成以下 SQL 语句:

    1. SELECT ... FROM users user WHERE user.registered = true AND (user.firstName = 'Timber' OR user.lastName = 'Saw')

    你可以根据需要组合尽可能多的ANDOR表达式。如果你多次使用.where,你将覆盖所有以前的WHERE表达式。注意:小心orWhere - 如果你使用带有ANDOR表达式的复杂表达式,请记住他们将无限制的叠加。有时你只需要创建一个 where 字符串,避免使用orWhere