The where clause in the Typeorm query builder instance is not functioning properly after its common usage

When fetching data for my relations, I opted to use QueryBuilder. In order to validate certain get request parameters before the index, I established a common QueryBuilder instance as shown below.

// Common Get Query
      const result = await this.reservationRepo
        .createQueryBuilder()
        .leftJoinAndSelect('Reservation.userId', 'userId')
        .leftJoinAndSelect('Reservation.companyId', 'companyId')
        .leftJoinAndSelect('Reservation.petId', 'petId')
        .orderBy(`Reservation.${sortBy}`, order)
        .where('Reservation.isArchived = :isArchived', { isArchived: false });

The validation logic I implemented looks like this;

//Check req starts is cancelled and return canceled data (getting data from db)
  if (getPaginationParamDto.status === GetReservationTypes.CANCELLED) {
    if (type === GetReservationTypes.COMPANY) {
      result.where('Reservation.companyId = :companyId', { companyId: `${searchID}` });
    } else {
      result.where('Reservation.userId = :userId', { userId: `${searchID}` });
    }
    result.where('Reservation.status = :status`, { status: getPaginationParamDto.status });

However, I encountered an issue with my where clause:

isArchived: false

it does not seem to be functioning correctly.

.where('Reservation.isArchived = :isArchived', { isArchived: false });

To resolve this problem, I had to place my isArchived where query after my logic implementation. Although it now works, the condition is still not being applied properly. Assistance in this matter would be greatly appreciated. Thank you.

Answer №1

As per the documentation provided by TypeORM regarding including WHERE conditions:

[...] If you use .where multiple times, it will replace all previous WHERE conditions.

Therefore, to apply multiple WHERE clauses to your query, consider using .andWhere() instead in your logic.

You could potentially do something like this:

const result = await this.reservationRepo
  .createQueryBuilder()
  .leftJoinAndSelect("Reservation.userId", "userId")
  .leftJoinAndSelect("Reservation.companyId", "companyId")
  .leftJoinAndSelect("Reservation.petId", "petId")
  .orderBy(`Reservation.${sortBy}`, order)
  .where("Reservation.isArchived = :isArchived", { isArchived: false });

// [...]

if (getPaginationParamDto.status === GetReservationTypes.CANCELLED) {

  if (type === GetReservationTypes.COMPANY) {
    result.andWhere("Reservation.companyId = :companyId", { companyId: `${searchID}` });
  } else {
    result.andWhere("Reservation.userId = :userId", { userId: `${searchID}` });
  }

  result.andWhere("Reservation.status = :status", { status: getPaginationParamDto.status });

// [...]

However, if you intend to add these extra WHERE conditions BEFORE executing the query, you may want to remove the await keyword from line 1. Make sure to finalize constructing the query before running it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The alternating colors in the sorting table are not visible due to the divs being hidden with the display set

I've come across a problem that has me stumped. So, there are two sorting filters on a table and one of them hides rows that don't apply, messing up the alternating colors. Take a look at the function that sorts and the CSS below. The issue is pr ...

Tips for transforming the input date value from Mui Datepicker

import * as React from "react"; import moment from "moment"; import TextField from "@mui/material/TextField"; import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs"; import { LocalizationProvider } from &quo ...

Trouble arises when trying to deploy React application on Github pages

After running npm run deploy and following all the steps, it shows that the project is published successfully. However, upon checking the Github hosted link, only my navbar component is visible. Despite setting up the routes correctly in app.js to display ...

Challenges in Implementing Shadows with Animations in ThreeJS MeshDepthMaterial

I'm facing an issue where casting shadows through transparent parts of my Mesh using the MeshDepthMaterial causes the shadows of animated objects to stop moving along with the animation. You can see an example of this problem here: https://jsfiddle.n ...

Tips for effectively managing asynchronous tasks

I keep getting different numbers every time my code runs. Can you tell me if I'm doing this the right way? Here's the code: export class GetPlanetsService { url='https://swapi.co/api/planets/?page='; planets:Planet[]=[]; headers: ...

Create a sequence of reactions using Selenium WebDriver

I am looking to gather a set of responses while browsing a website, and then "recreate" the process using those responses. Upon exploring an different discussion, I stumbled upon this method for rendering HTML: content = requests.get("https://stackoverfl ...

Executing a nested function before moving on to the subsequent code statements

I have a requirement where certain functions in my codebase need to check if a user is logged in before proceeding. Instead of duplicating this check logic, I want to call a single getUser() function each time. Here is the order of operations for the func ...

What is the designated action or code in question?

let specialty = ''; function isVegetarian() { }; function isLowSodium() { }; export { specialty, isVegetarian }; export { specialty, isVegetarian }; The explanation from the editor was as follows: When exporting objects, it is done by the ...

"Learn the art of refreshing data in AngularJS following the use of $emit event handling

I am in need of assistance with AngularJS. How can I re-initialize a variable in scope after using emit? Here is an example code snippet: $scope.uiConfig = {title: "example"}; $scope.$emit('myCustomCalendar', 'Data to send'); $scop ...

Unable to open file after downloading via AJAX

I am facing an issue while trying to download a file using an Ajax request. Although the file is successfully downloaded, I am unable to open it. I am seeking assistance with the provided details below. Thank you. On a JSP page, there is a list ...

Utilizing a third-party API within the next/api endpoint

I've recently started working with NEXTJS and developed a weather application. I'm integrating the openweather API, but I'm unsure how to use it within the next/api. I attempted creating a file named today.js inside the next/api directory an ...

Automatically assigning IDs to all elements on an Angular webpage

We are currently developing an enterprise web application and have brought on board an e2e test engineer to automate tests. The test engineer has requested that we assign IDs to all elements in our pages. Is there a tool or method available to automatical ...

I constantly encounter a TypeError message that returns as undefined

I'm currently facing an issue while trying to run my Node.js server locally. The error message I keep receiving is: /Users/rogerjorns/Desktop/templateassignment/node_modules/express/lib/router/index.js:458 throw new TypeError('Router.use() ...

Tips for inserting a page break after every item in a loop in Visualforce when generating a PDF document

I need help with rendering a VF page as PDF. The VF page iterates over a list of account records using the repeat tag. I want to apply a page break for each element in the repeat tag. The code below is working, but it has an issue - it shows an empty PDF p ...

Encountering a glitch while trying to utilize History.js

I've decided to incorporate History.js into my web application to address the lack of support for history.pushState() in Internet Explorer. After reviewing various demos and tutorials, I have written this code snippet: var historyJs = window.History; ...

Utilize Javascript/Jquery to categorize JSON data based on the days of the week (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)

A function is provided below that retrieves data for a chart. The output produced by this function is structured as follows: [Object { date=Date, value=112, volume=1469}, Object { date=Date, value=124, volume=539}, Object { date=Date, value=114, vo ...

Tips for Accessing the TextInput Content in React Native

My code is currently experiencing a bug where I am getting an undefined object type when trying to console log user input. Below is the code snippet I am working with. Can you help me identify and correct the issue? export default function App() { con ...

Guide on programmatically changing the position of a shape in SVG

Check out this tutorial on how to make SVG elements draggable using JQuery and Jquery-svg. The accepted answer provides an implementation for moving a circle by changing the cx and cy attributes. But how can I achieve drag-and-drop functionality for a pol ...

Guide on converting JSON data into a PDF using TypeScript

I need to take JSON data and convert it into a PDF format when the PDF button is clicked in the UI. I have tried a few things but I'm struggling with binding the response to the PDF function. My goal is to display values from the "actualExpenses" arra ...

The Benefits of Semantic Class Names compared to Microdata

As I strive to use semantic class names, my exploration of microdata and SEO raises a question: Is it necessary to use both? Compare these two HTML snippets representing an event: Using CSS classes: <div class="event" itemscope itemtype="http://schema ...