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

Time:09-20

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!!!

CodePudding user response:

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 })
      })
    )
  }

CodePudding user response:

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

  • Related