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

Javascript conditional testing

I need help coding a <div> to display only if the numeric input is 18 or above and the YO option is chosen. Any guidance on this would be highly appreciated. See the code snippet below. <input type=numeric id=ageSelf ng-model="ageSelf" style="c ...

Tips to prevent redirection in a JavaScript function

When a user clicks on a specific link, the HideN function is triggered. Here's an example: <a href="<?php echo $dn5['link']; ?>" onclick="HideN('<?php echo $dn5['id'];?>','<?php echo $dn5['fro ...

Guide to showcasing a placeholder in MUI's Select component

How can I add the placeholder "Select a brand" to this select element? I've tried different options with no luck. Here is the code snippet I am working with: <FormControl fullWidth> <InputLabel id="demo-multiple-name-label" ...

The lack of synchronization between the updated state in one function and its counterpart is causing discrepancies, resulting in the incorrect information being sent to the API

Whenever I press the following button: <Button onClick={(e) => { addToCard(item); handleprisma(); }} > add to cart </Button> This function is meant to add the item to my shopping cart: const addToCard = (item) => { co ...

Managing browser navigation within a web application

I am currently developing a web-based application for internal use in the company I work for. The application is quite intricate, featuring numerous forms that will enable users to both view and input data, which will then be stored in a database upon savi ...

What impact do the input values of an Angular reactive form have on the DOM?

I am currently working on developing a UI wizard app using Angular (reactive forms) version 6/7. The main purpose of this app is to enhance the product page of an ecommerce platform such as Shopify or WordPress. I am utilizing angular material radio inputs ...

Error injecting Angular components

Here is the structure of my HTML file: <html> <head> <title>PLD Interaction pattern</title> <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/> </head> <body ng-app="myT ...

Setting up Firebase App Check in an Angular projectWould you like to know

I have a question about initializing Firebase app check with Angular. I am currently using AngularFire, but I'm not sure how to initialize Firebase app check before using any services. The documentation provides the following initialization code to b ...

Update the content on the webpage to display the SQL data generated by selecting options from various dropdown

My database table is structured like this: Name │ Favorite Color │ Age │ Pet ────────┼────────────────┼───────┼─────── Rupert │ Green │ 21 │ ...

Ways to implement Formik to output a boolean value?

Currently, I am facing an issue retrieving a value from Formik. While it works perfectly fine with a Textfield component, I am unable to fetch the value of my switcher (which is a boolean). The setup for my file and switcher looks like this: <div clas ...

What is preventing the addition of links to the navigation bar when using a sticky navigation bar?

Currently, I am in the process of developing a blog website using Django. One of the features I have successfully implemented is a sticky navigation bar. However, I am facing a challenge with adding links to the menu on the navigation bar due to existing ...

In Javascript, where are declared classes stored?

When working in a browser environment like Firefox 60+, I've encountered an issue while attempting to retrieve a class from the global window object: class c{}; console.log(window.c); // undefined This is peculiar, as for any other declaration, it w ...

Immersive pop-up interface displaying a variety of embedded videos simultaneously

I am a beginner in JavaScript and I came across a CodePen that does exactly what I need, but it currently only works for one embedded video. What I aim to achieve is similar functionality, but with 6 videos. (function ($) { 'use strict'; ...

Angular Dom does not update when invoking a function within a separate component

Greetings everyone! I am facing a situation where one component (let's name it recipe component) has a reference to another component (named grocery component). The method in my recipe component uses the reference to the grocery component to call a s ...

Handling multiple promises with JavaScript/Express Promise.all()

For my latest project, I am developing a movie discussion forum where users can create profiles and list their favorite films. To display the details of these movies, I have integrated the OMDB API with a backend route built using Express. In my initial t ...

The term 'components' has not been defined (no-undef)

Recently integrated Vue into an existing project and encountered a peculiar linting error: error: 'components' is not defined (no-undef) at src/App.vue:13:3: 11 | 12 | @Component({ > 13 | components: { HelloWorld }, | ^ 14 | }) ...

Clicking on the button has no effect whatsoever

I'm currently dealing with a button on my webpage that seems to be causing me some trouble: <script> function changeMap() { container.setMap(oMap); } </script> <button onClick="changeMap"> Click here </button> Upon inspe ...

Learn how to implement React Redux using React Hooks and correctly use the useDispatch function while ensuring type-checking

I'm curious about the implementation of Redux with Typescript in a React App. I have set up type-checking on Reducer and I'm using useTypedSelector from react-redux. The only issue I have is with loose type-checking inside the case statements of ...

What is the best way to efficiently load all of my web applications within the web application that I am currently developing?

https://i.stack.imgur.com/IAjIW.png Greetings! I am currently a novice Web Developer and here is my current situation: I am working on developing 3 web applications, with one additional application that will load all three of them. Please refer to the im ...

extract keys and values from an array of objects

I would like assistance with removing any objects where the inspectionScheduleQuestionId is null using JS. How can we achieve this? Thank you. #data const data = [ { "id": 0, "inspectionScheduleQuestionId": 1, ...