Utilizing TypeORM to selectively choose data in OneToMany relationships

I am looking to create a TypeORM query that pulls data from the database. Specifically, I want to retrieve all clients who have made a purchase but have not initiated a return. Here is the structure of the database:

Clients:

  • Id (Int, primary column)
  • Purchase_Id (only one purchase possible for a client; refers to Id of Purchases; nullable)

Purchases:

  • Id (Int, primary column)

Returns:

  • Id (Int, primary column)
  • Purchase_Id (several returns per purchase are possible; refers to Id of Purchases)

To fetch all clients along with their purchases and returns, I have successfully used this code:

let query = this.clientRepo
  .createQueryBuilder('client')
  .select()
  .leftJoinAndSelect('client.purchase', 'purchase')
  .leftJoinAndSelect('purchase.returns', 'returns');

However, my challenge now is to apply a filter to only display customers who have initiated a return. This is where I encountered some errors. Here are the attempts I made and the corresponding issues:

query = query.where('purchase.returns IS NULL');

(Error: QueryFailedError: Error: Invalid column name 'returns'.)

query = query.where('client.purchase IS NOT NULL and purchase.returns IS NULL');

(Error: Cannot query across one-to-many for property returns)

query = query.where('purchase.returns IS (:...returnValues)', {returnValues: []});

(Error: QueryFailedError: Error: Invalid usage of the option NEXT in the FETCH statement.)

I am relatively new to TypeORM. Any advice on how to solve this issue would be greatly appreciated! Thank you.

Answer №1

Alright, here's the solution I discovered. In case anyone requires it in the future:

query = query.where('client.purchase IS NOT NULL AND returns.Id IS NULL');

The reason for using "returns.Id" instead of "purchase.Id" is that "purchase" serves as an alias already referring to the Id column. This column can have a null or non-null value.
In contrast to purchase, the alias "returns" points to a table and not a column. A table cannot be null or non-null, hence you need to specify a column like "Id".

My understanding is that this difference in references stems from the client->purchase relation being one-to-one, while purchase->returns is many-to-one.

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

Utilizing JSON data to populate a modal window in HTML

How can I incorporate JSON data into an HTML modal window? I have a set of 12 buttons, and when a user clicks on one, I want to display the corresponding month's information from a JSON file. let myJson; $(`button`).on(`click`, function() { let ...

Using jQuery Datepicker, showcase two distinct datepickers on a single page

Currently, I am utilizing the jQuery [Datepicker][1] on a website, but I am facing challenges when attempting to display two datepickers on the same page in different manners. The first one should only appear once you click the text box, and once a date i ...

Load various types of classes and run functions with matching names

I have encountered a challenging issue that needs to be resolved. Imagine having multiple classes located in a directory named services. These classes all include a constructor() and send() method. Examples of such classes can be Discord, Slack, SMS, etc. ...

Is Typescript the Ultimate Replacement for propTypes in React Development?

After diving into Typescript for the first time and exploring related articles, it appears that when using Typescript with React, propTypes definitions may no longer be necessary. However, upon examining some of the most popular React Component Libraries: ...

Utilizing Angular to efficiently download and showcase PDF files

Presently utilizing https://github.com/stranger82/angular-utf8-base64 as well as https://github.com/eligrey/FileSaver.js/ for the purpose of decoding a base64 encoded PDF file that I am fetching from a rest API. It successfully decodes and downloads, ...

The preflight request's response failed to meet the access control criteria due to the absence of the 'Access-Control-Allow-Origin' header

I encountered an issue while using ngResource to call a REST API hosted on Amazon Web Services: Upon making the request to , I received the following error message: "XMLHttpRequest cannot load. Response to preflight request doesn't pass access cont ...

Challenges with Knockout.js Virtual Elements in Different Environments

I am facing a peculiar issue where a virtual knockout template fails to bind correctly when accessed remotely, yet functions perfectly when viewed locally. You can find the problematic page here: Here is the template I am using: <ul> <!-- k ...

When it comes to TypeScript, it feels like my interface can accept anything I throw at it, and it struggles to grasp how I've implemented and imported redux-toolkit and styled components

My Current Struggle: Errors in Typescript are occurring seemingly at random. The interface in my index.tsx file doesn't align with the object it should describe, yet no red flags are raised. On top of that: An error pops up when attempting to import ...

How can I extract the value from the object returned by an AJAX call?

HTML file <div class="container"> <table id="headerTable" class="table table-bordered"> <thead> <tr> <th colspan="2">Header</th> </tr> </thead> <tbody> <c:forEach item ...

Transforming NodeJS Express HTTP responses into strings for AngularJS consumption

I have been working on creating an AngularJS program that communicates with an Express/Node.js API and a MySQL database. On the login page, I am successfully able to call the API which connects to MySQL. Depending on the correct combination of username an ...

Breaking down JavaScript arrays into smaller parts can be referred to

Our dataset consists of around 40,000 entries that failed to synchronize with an external system. The external system requires the data to be in the form of subarrays sorted by ID and created date ascending, taken from the main array itself. Each ID can ha ...

Textarea generated on-the-fly without any assigned value

My goal is to enable users to edit the text within a paragraph on a website. I am attempting to replace the <p> tags with <textarea> tags using the .replaceWith() function. However, when I try to retrieve the value of the textarea, it comes bac ...

Establish an angular scope within the DOM element

I am facing a challenge in creating a new Angular scope and attaching it to a DOM element. The situation is complicated by the fact that I am working on modifying a third-party control and cannot simply use a directive. My approach so far has been: ... = ...

Simplified user interface for detecting radio button clicks

Currently working on a form that includes radio buttons, where an update function is triggered whenever there is a user input change. The challenge I am facing is how to incorporate user-friendly radio buttons with a larger button area encompassing both t ...

Delete the final character from the value stored in the map

After retrieving data from the backend, I receive: {"Item":{"userEmail":"b","Username":"bUsername","Push":"sdsdsd","Password":"sdsds","Buddy":{"datatype":"SS","contents":{"Drake":"Drake","Ola":"Ola","b":"b","d":"d"}}}} Utilizing Object.Keys, I filter ...

Transfer a variable from one PHP page to another and navigate between the two pages

I am just starting to learn PHP and I have a scenario where I need to retrieve the last ID from the database. For each ID, I need to fetch the state and the associated link. If the state is equal to 1, then I need to extract some content from the link (whi ...

Dealing with errors within nested requests while using switchMap with RxJS

I am faced with a situation where I need to make 2 dependent API calls: the getCars call requires the user id obtained from getUser. There is a possibility that a user may not have any cars, resulting in a 404 error from the API. How can I handle this sc ...

Looking for Assistance with Enhancing a Fascinating MySQL Query

Query Performance Boost Seeking assistance in enhancing the speed of this database query. The query's purpose is to calculate the total sum of periods that meet specific conditions associated with cases. Currently, the query execution time is approx ...

Attempting to reset my react-final-form fields led to receiving an empty object as the values instead

Currently, I am facing a situation where I need to clear all field values except for "retainThisObj" upon the initial page load. The problem I encountered is that my { } ended up empty, meaning that my "retainThisObj" was also deleted. ...

Using Nuxtjs/Toast with personalized image emblems

Would it be possible to include an icon in a toast error message, or is there a need to install another module for this functionality? I am currently using vue and attempting to integrate a component as an icon, but so far without success. this.$toast.er ...