简体   繁体   中英

How to make Typeorm QueryBuilder work for AND and OR inside AND operators?

Hi I have written the following Typeform Querybuilder code...

queryBuilder.andWhere('tdm.type =:type', { type: filters.type })
    queryBuilder.andWhere('tdm.form =:form', { form: filters.formId })

    if (filters.orLeadId && filters.orSupportId) {
      queryBuilder.andWhere(subQb => {
        subQb.where('tdm.leadId = :lead', { lead: filters.orLeadId }),
          subQb.orWhere('tdm.supportId = :support', {
            support: filters.orSupportId,
          })
      })
    }

But it results in neglecting the andWhere Operators and results in the following query

SELECT "tdm"."id" AS "tdm_id", "tdm"."form_id" AS "tdm_form_id" FROM "tdm" "tdm" WHERE "tdm"."lead_id" = $1 OR "tdm"."support_id" = $2

Can anyone help me to get the above code right please!!!

I refactored the code as follows

 if (filters.orLeadId && filters.orSupportId) {
      queryBuilder.andWhere(
        new Brackets(subQb => {
          subQb
            .where('tdm.leadId = :lead', { lead: filters.orLeadId })
            .orWhere('tdm.supportId = :support', {
              support: filters.orSupportId,
            })
        })
      )

I followed TypeORM find where conditions AND OR chaining and its working like a charm

I think new Brackets will have to be used here so the clause containing the two conditions to be OR'ed are inside the brackets after AND as it would be when writing in plain SQL

queryBuilder
  .andWhere('tdm.type =:type', { type: filters.type })
  .andWhere('tdm.form =:form', { form: filters.formId })

  if (filters.orLeadId && filters.orSupportId) {
    queryBuilder.andWhere(
      new Brackets(subQb => {
        subQb
          .where('tdm.leadId = :lead', { lead: filters.orLeadId })
          .orWhere('tdm.supportId = :support', { support: filters.orSupportId })
      })
    )
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM