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

Error: The React component throws a TypeError because it is unable to read the property 'map' from an undefined source

I encountered the following error TypeError: Cannot read property 'map' of undefined at ListItemFactory.ts:84:57 at The specific line where the error occurs is: return announcementitems=json.value.map((v,i)=>( To provide mor ...

Error: The sqlite database for Android could not be located

Running my code (my app) from Android Studio with AVD manager worked smoothly. Initially, I encountered an issue with the database not being found there, but I managed to resolve it by using Monitor (DDMS) and placing the file in the correct location: /dat ...

The parameter selection in the select statement is set to be optional with the condition

I am encountering an issue with a function that has an optional parameter. My goal is to display all records if the parameter is not specified, and only the record with the specified ID if it is. I attempted the following code, but unfortunately, it is not ...

Incorporating dynamic dependency injection in Angular 2 through the use of @Input()

Let's consider a scenario where an Angular 2 component-directive needs to dynamically determine the injected dependency it uses based on an @Input(). For example, I would like to be able to specify <trendy-directive use="'serviceA'"> ...

Tips for submitting a request following a change in the variable

I am in the process of developing a React application and I have implemented Auth0 for authentication. My goal is to initiate an HTTP request upon page refresh, but only if the variable isLoading is false. This way, I can access the user object once the ...

Using the index in Vue.js to locate a method within an HTML file

Currently, I am attempting to make use of the reference "index" located within <tr v-for="(note, index) in noteList" v-bind:key="index" in order to call shareToPublic(index). The method selectedID() allows for the selection of the ...

I can't seem to catch my Zod error, even though 'express-async-errors' is already installed. What could be causing this issue?

I've been working on developing an API, but I'm facing issues with setting up a global error controller using Zod. It seems that the global error handler is not being called even though I'm using express-async-errors. Below is my error mana ...

Managing a digital timepiece within a multiplayer gaming environment

I'm currently developing a fast-paced game where players control a block resembling a clock. To accurately calculate the time taken by each player to make moves, I store the start time of the game and record the timestamp of every move in the databas ...

Instructions for removing or replacing a specific substring in a column using a pattern such as %[%]%

In my database table, there is a column called message that contains expressions like [example] or [bla bla]. My goal is to remove the brackets [] as well as any text within them. For instance: input: its a string [text to remove including braces] to re ...

Ensuring Map Safety in Typescript

Imagine having a Map structure like the one found in file CategoryMap.ts export default new Map<number, SubCategory[]>([ [11, [100, 101]], [12, [102, 103]], ... ]) Is there a way to create a type guard for this Map? import categoryMap fro ...

Dynamically resizing a property in the DOM with Angular

Could someone help me with an issue I'm having regarding resizing items on the screen in Angular when the browser window size changes? Here is my code snippet: // TS File height: number = 2.5; objHeight:number; screenHeight:number = window.innerHeig ...

Is there a way to display the number of search results in the CodeMirror editor?

After conducting some research on how to integrate the search result count in Codemirror like the provided image, I was unable to find any solutions. I am currently working with Angular and utilizing ngx-codemirror, which led me to realize that editing the ...

How can an array of file paths be transformed into a tree structure?

I am looking to transform a list of file and folder paths into a tree object structure (an array of objects where the children points to the array itself): type TreeItem<T> = { title: T key: T type: 'tree' | 'blob' childr ...

Running the NPM build command results in an error specifically related to an HTML file

I encountered an issue in my AngularJS application when running the command: npm run build -- -prod The error message I received was: ERROR in ng:///home/directoryling/appname-play.component.html (173,41): The left-hand side of an arithmetic operation ...

Error message in Vue3 with TypeScript: When using global components, you may encounter the error "JSX element type '___' does not have any construct or call signatures.ts(2604)."

Each globally registered component suddenly displays a red TypeScript squiggle in the markup! Surprisingly, the app continues to function without any visible errors! This issue arises with all components, whether they are custom-made or third-party libr ...

Warning: Potential spacing issues when dynamically adjusting Material UI Grid using Typescript

When working with Typescript, I encountered an error related to spacing values: TS2322: Type 'number' is not assignable to type 'boolean | 7 | 2 | 10 | 1 | 3 | 4 | 5 | 6 | 8 | "auto" | 9 | 11 | 12'. No lint errors found Version: typesc ...

What is the best way to perform multiple OR comparisons in SQL when searching through a list?

I am encountering an issue with the first comma in this code snippet. It seems to be causing a syntax error. if (@BAAgtNo = '0000ZV') and (@ProfileNumber = '902876'***,*** '903673', '903674', '903675', ...

Perform a SQL query with specified conditions in order to retrieve another record containing a superior value

Displayed below is a table containing some data: SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; CREATE TABLE `activities` ( `id` int(10) UNSIGNED NOT NULL, `project_id` int(10) UNSIGNED NOT NULL, `user_id` int(10) UNSIGNED NOT NULL, `task_hour` double( ...

Deciphering the meaning behind a statement

Currently working on an SSRS report with a SQL statement provided for data retrieval. Attempting to comprehend the if statement within the given SQL query. Initially in a non-TSQL format, the code was converted accordingly. Uncertain about how to handle th ...

React Native ScrollView ref issue resolved successfully

I'm trying to automatically scroll to the bottom of a flatlist, so here's what I have: const scrollViewRef = useRef(); //my scroll view <ScrollView ref={scrollViewRef} onContentSizeChange={() => { scrollViewRef.current.scr ...