Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

324
Views
TypeORM Conditional Selection with OneToMany

I need to write a TypeORM code to generate a query that selects all clients who made a purchase but did not initiate a return. This is the database structure:

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)

This is what I use to get all the clients, their purchases and returns. This works:

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

Now, I am trying to add a filter to only see customers who initiated a return. This is what I tried and what errors I got:

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 new to TypeORM. How to resolve this problem? Thank you very much in advance!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Ok, I found an answer. If anyone needs it for the future:

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

The reason you write "returns.Id", but not "purchase.Id" is that "purchase" is an alias that already refers to the Id column. And a column can be null or non-null.
Unlike purchase, "returns" alias refers to a table, not a column. A table can't be null or non-null, so you need to get a column, like "Id".

From what I understand, this difference in references comes from the client->purchase relation being one-to-one, but purchase->returns being many-to-one

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!