Update multiple records at once in Typeorm, but only if they already exist in the specified body

Hypotheses

  • Multiple occurrences of a single entity named Product are present.

  • The Product entity has three attributes namely 1) id, 2) name, and 3) active.

  • The current instances stored in the database are as follows:

    [ { id:1, name:'A', active: 0 }, { id:2, name:'B', active: 1 }, { id:3, name:'C', active: 0 }, ]

Issue

The goal is to modify certain properties of multiple instances based on their IDs using a query similar to the one below:

Product.update(
  [1,2] , // ids
  {
    name: 'example'
  }
)

The desired outcome should be:

[
  {
    id:1,
    name:'example',
    active: 0
  },
  {
    id:2,
    name:'example',
    active: 1
  },
  {
    id:3,
    name:'C',
    active: 0
  },
]

However, this query overrides the other properties, specifically the active attribute, setting it to default. The result obtained is as follows:

[
  {
    id:1,
    name:'example',
    active: 0
  },
  {
    id:2,
    name:'example',
    active: 0 // incorrect value!
  },
  {
    id:3,
    name:'C',
    active: 0
  },
]

Inquiries

  1. Is there a way to only update specified properties in the query (e.g., name)?
  2. How can this issue be resolved using the save method? (Considering that passing ids to the save method is not possible)

Answer №1

This issue was resolved by implementing the createQueryBuilder method like so:

await getManager()
  .createQueryBuilder()
  .update(Product)
  .set({
    name: 'example'
  })
  .where('id IN (:ids)', { ids: [1,2] })
  .execute();

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

The disparity when comparing the total of two products is greater than zero

https://i.sstatic.net/u6e3r.png I am trying to calculate the difference between the sum of T_No where Transactions are equal to R and the sum of T_No where Transactions are equal to D. The result must be greater than zero for a specific CustomerID, which ...

Exploring MySQL: Counting Techniques Using PHP

I need assistance with creating a query in codeigniter to display specific counts. For example, I want to select items with atr_id 90 and 56. $this->db->where('atr_id', 90); $this->db->or_where('atr_id', 56); Here is the s ...

Execute a function once an observable variable has been successfully initialized

I'm currently putting together a chat application using socket.io in Angular. I've encountered an issue where I can't seem to execute a particular code or function right after an observable variable is initialized through subscription. The i ...

Prevent identical objects from being interchangeable in Typescript

I have a situation where I frequently use a StringToString interface: interface StringToString { [key: string]: string; } There are instances when I need to switch the keys and values in my objects. In this scenario, the keys become values and the val ...

Looping issue with ForEach in Typscript with Firebase Functions

While browsing through various questions on this topic, I've noticed that the specific answers provided don't quite fit my situation. My query involves converting a Google Firebase RTB datasnapshot into an array of custom objects, each representi ...

Determine if dates overlap using MySQL or PHP programming

Can someone help me with this challenge? I have a MySQL table structured like this id | program_name | start_date | end_date 1 | program1 | 2014-12-01 | 2014-12-07 Now, when inserting a new record via PHP for id 1, I need to check if there is any o ...

Creating a versatile function that can function with or without promises is a valuable skill to have

I am currently working on developing a versatile sort function that can function with or without promises seamlessly. The intended structure of the function should look something like this: function sort<T>(list: T[], fn: (item: T) => string | nu ...

The Tailwind CSS Chrome extension is causing disruptions on the websites I view

Currently, I am in the process of creating a chrome extension using various tools like React, Typescript, TailwindCSS, and a custom Webpack configuration. To enhance user experience, I have modified the default action in manifest.json so that clicking on t ...

Understanding Typescript event handling in React

Encountering issues when attempting to build my React/Typescript app using the MouseEvent type in an event handler: private ButtonClickHandler(event: MouseEvent): void { ... } The error message received is as follows: error TS2322: Type '{ onCl ...

Troubleshooting tips for accessing queryParams in ngOnInit when using Angular routing method with queryParams

Currently in the process of learning Angular Routing, I encountered an error. In the course component, I attempted to make changes to the web content by utilizing queryParams and a variable editMode: boolean with its default value set to false. Link to St ...

Sending Angular form data as an array format

Currently, I am sending a post request to the backend with only one input field. When I check the console, my request is displayed as "request." However, the backend actually requires the request to be formatted in an array such as ["request"]. ...

Removing/modifying selected choices in an element

I have implemented a material ui select element with the ability to make multiple selections using checkboxes. My query is, can I incorporate the functionality to delete or update names directly from the select element itself? For instance, by clicking on ...

What is the method for generating a data type from an array of strings using TypeScript?

Is there a more efficient way to create a TypeScript type based on an array of strings without duplicating values in an Enum declaration? I am using version 2.6.2 and have a long array of colors that I want to convert into a type. Here is what I envision: ...

Comparing Angular2: The benefits of subscribing to Observables versus using singleton

Summary: Link to example What is the benefit of using a service's local variable instead of subscribing to an observable within the service? Illustrative Example: In the provided plunker, there are two components and a service. Both components sha ...

Is it possible to store multiple records in MySQL with identical user information, except for the phone number?

Is it possible to have the same username and email in one table, but with different phone numbers stored in another table linked by the user ID? Also, what might be the issue if I duplicate user information records in the user table, each with a different ...

SQL / Coalesce - Inaccurate column reference

Issue encountered with the query provided below! QUERY: SELECT COALESCE(date(date_field), 'Total') AS "date_field_group", COUNT( id_field ) AS "Number of bookings", CONCAT( REPLACE( REPLACE( FORMAT( SUM( price1 ) , 2 ) , ',', ' ...

The Zend DB fetchAll function encounters issues when retrieving data from the "id" column containing values greater than 926

I have been encountering an issue with retrieving data from a table using Zend DB fetchAll(). The table consists of 475 rows, with IDs ranging from 755 to 1230. However, when attempting to fetch the data using: $select = $db->select()->from('pr ...

PHP: Creating a dynamic drop down menu with grouped options

I'm currently working on a drop-down menu that utilizes HTML optgroups to categorize employees based on the groups they belong to. Below is the MySQL query and output that I have been working with: <select name="dropdownmenu"> <optgroup ...

Is it possible to incorporate WHERE into UPDATE statements?

After working on my login and registration system, I encountered a challenge with the code in my registration system. Here is the snippet: <?php $sql3="UPDATE users SET firstname='$firstname', lastname='$lastname', ...

Error in Typescript tuple linting is inconsistent in vscode

While following a tutorial video on utilizing types in TypeScript, I encountered an inconsistency between my text editor's linting and the content of the video. The video displays this: https://i.sstatic.net/awm9f.png However, mine shows like this: ...