The OR operator in TypeORM allows for more flexibility in querying multiple conditions

Is there any OR operator in TypeORM that I missed in the documentation or source code?

I'm attempting to conduct a simple search using a repository.

db.getRepository(MyModel).find({
  name : "john",
  lastName: "doe"
})

I am aware that this creates an AND operation, but I require an OR operation like in SQL:

name='john' OR lastName='doe'

Do I have to resort to using the query builder for something as basic as this?

Answer №1

queryBuilder.getRepository(MyModel).find({
  where: [
      { firstName: "john" },
      { lastName: "smith" }
  ]
})

Provide an array as the parameter for where

Answer №2

To enhance your query with both "OR" and additional "AND" conditions, follow these steps.

db.getRepository(MyModel).find({
  where: [
      { name: "john", lastName: "doe" },
      { age: 20 }
  ]
})

This will generate the following result

select * from model where (name = "john" and lastname = "doe") OR age = 20

We hope this explanation is beneficial to you.

Answer №3

After encountering the same issue, I found a solution using the QueryBuilder.

Here is an example of how it can be implemented:

return await getRepository(MyModel)
  .createQueryBuilder()
  .where("name = :name OR lastName = :lastName", {
    name: "john",
    lastName: "doe"
  })
  .getMany();

Answer №4

When utilizing the OR operator within a sub-clause, it is necessary to duplicate the main-clause

userRepository.find({
  where: [
    {
      firstName: 'Timber',
      lastName: 'Saw',
      project: {
        name: 'TypeORM',
      },
    },
    {
      firstName: 'Timber',
      lastName: 'Saw',
      project: {
        initials: 'TORM',
      },
    },
  ],
});

Retrieve all records of individuals named Timber Saw who have projects with either name = "TypeORM" or initials = "TORM”.

Answer №5

Starting from version 0.3.18 (released on January 3, 2024), TypeORM has introduced support for the Or operator in its basic .find* methods:

const users = await db.getRepository(User).findBy({
    name: Or(Equal("John"), ILike("Jane%")),
})
-- This will generate the following SQL query:
SELECT * FROM "user" WHERE "name" = 'John' OR "name" ILIKE 'Jane%'

Although this feature may not address your specific scenario, it can be beneficial to other users when dealing with queries involving a single field.

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

Using TypeScript and Angular to remove properties from an object

My RandomValue class and WeatherForecast class are causing me some trouble. The WeatherForecast class is functioning properly, populating the table with data as expected. However, the RandomValues class/interface appears to be returning a list of objects w ...

What is the best method to retrieve HTTP headers from the backend and simultaneously send HTTP parameters to it in ASP.NET Core and Angular?

I am currently working with Angular 15 and ASP.NET Core 5. The backend retrieves paged items based on the parameters pageSize and pageIndex. Once the action method receives the pageSize and pageIndex parameters, it sends both the paged items and the total ...

gRPC error: "unable to connect to the specified address" while running a NestJS application on Docker

I am encountering this particular error message when trying to run my NestJS application in a Docker container with gRPC: { "created": "@1616799250.993753300", "description": "Only 1 addresses added ou ...

What is the best way to generate a switch statement based on an enum type that will automatically include a case for each enum member?

While Visual Studio Professional has this feature, I am unsure how to achieve it in VS Code. Take for instance the following Colors enum: enum Colors { Red, Blue, When writing a switch statement like this: function getColor(colors: Colors) { swi ...

Unexpected Issue: Angular 12 Encounters JIT Compiler Unavailability

Lately, I've been encountering a persistent issue with an error message: Uncaught Error: JIT compiler unavailable. Ever since I upgraded from Angular version 8 to 12, whenever I run the ng build --prod --output-path = dist command and build Angular, e ...

Creating a Dynamic Table with Angular 6 - Automating the Population of Content Values

I have a task of populating a table with data from a JSON file. Take a look at the following code snippet: <table> <thead> <tr> <th *ngFor="let datakeys of listData[0] | keys">{{ datakeys }}</th> </tr> < ...

Performing conditional filtering in Python Pandas using GroupBy, similar to the "If A and not B" where

Trying to figure out how to achieve the following using pandas and groupby: Dataframes A and B share a common index variable, with A having 20 unique index values and B having 5. I aim to create dataframe C, which contains rows with indices from A th ...

typescript: textual depiction of a generic type T

I have a requirement to develop a method that is capable of handling generic data types, and I need to incorporate the type information into the method Our API requires passing the entity name as a parameter: http://server/api/fetch/Entity/123 It's ...

Testing Vue components with Typescript and Jest does not display the expected values in the HTML output

Recently, I decided to focus on Test-Driven Development (TDD) using Typescript, so I started a new Vue project with vue-cli. I specifically chose Vue3, Typescript, and Jest for this project. However, when I ran the unit test initially, it failed to execute ...

What is the best way to transmit a JSON object to REST services using Angular?

Whenever I attempt to send the JSON object to REST services, I encounter an error that looks like this: http://localhost:8080/api/v1/cardLimit 400 (Bad Request); JSON Object Example: public class GameLimit implements Serializable { private stati ...

The IDE is able to detect interface extensions in d.ts files, but TypeScript is not recognizing them

When developing in ES6 style module inclusion within WebStorm, I encountered an issue with my Express app and a custom d.ts file. The d.ts file contains middleware that alters objects, and the structure looks like this: declare module Express { export ...

Using TypeScript with React Bootstrap's <Col> component and setting the align attribute to 'center' can trigger a TS2322 warning

The React app I'm working on includes the code below. The Col component is imported from React-bootstrap <Col md={5} align="center"> This is a column </Col> When using Typescript, I received the following warning: ...

Discovering the highest value within an array of objects

I have a collection of peaks in the following format: peaks = 0: {intervalId: 7, time: 1520290800000, value: 54.95125000000001} 1: {intervalId: 7, time: 1520377200000, value: 49.01083333333333} and so on. I am looking to determine the peak with the hig ...

The latest update of WebStorm in 2016.3 has brought to light an error related to the experimental support for decorators, which may undergo changes in forthcoming

Hello, I recently updated to the latest WebStorm version and encountered this error message: Error:(52, 14) TS1219:Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' ...

Utilize an array of observables with the zip and read function

I'm struggling with putting an array of observables into Observable.zip. I need to create a function that reads values from this dynamically sized array, but I'm not sure how to go about it. Does anyone have any suggestions? import {Observable} ...

Parsing JSON results in the return of two objects

I am analyzing a JSON file, expecting it to return Message[] using a promise. This code is similar to the one utilized in the Heroes sample project found in HTTP documentation { "data": [ {"id":"1","commid":"0","subject":"test1subject","body":" ...

Why does Angular throw a length-related error, while I am able to retrieve the length using console log if needed?

It appears that Angular is not receiving the correct data type it expects, yet the lack of errors in the terminal is puzzling. However, the console output states: https://i.stack.imgur.com/1xPsg.jpg If the length property can be detected (highlighted in ...

Setting a default value for the dropdown in Angular is essential for ensuring a smooth

<select [(ngModel)]="detail.State" (ngModelChange) ="onStateChange()" class="form-control"> <option [ngValue]="null" disabled selected>Select State</option> <option * ...

Angular Igx-calendar User Interface Component

I need assistance with implementing a form that includes a calendar for users to select specific dates. Below is the code snippet: Here is the HTML component file (about.component.html): <form [formGroup]="angForm" class="form-element"> <d ...

How can AJAX be utilized to show search results dynamically?

At the moment, I have a PHP page that pulls a list of results from my SQL database and displays the ID and names. There is a search bar at the top where you can search for keywords in the "name" field, and when you click on search, it takes you to a new p ...