Using TypeORM to update a relation and set it to NULL

My challenge involves managing this specific Entity

@Entity({ name: 'orders' })
export class Order {
 ...

  @ManyToOne(() => BulkOrder, (bulkOrder) => bulkOrder.orders)
  bulkOrder?: BulkOrder
}

In my update process, I am attempting to reset the relation to null

.createQueryBuilder()
.update(Order)
.set({ status: OrderStatus.OPEN, bulkOrder: undefined }).
where(...).execute()

However, it seems that the bulkOrder field is not being updated correctly, as indicated by the generated query

query: UPDATE "orders" SET "status" = $1, "updated_at" = CURRENT_TIMESTAMP WHERE ("id" IN ($2, $3) ...

Is there a way to successfully set the relation to null? While I understand I could manually set it to null and save the entity, using a query builder is necessary in order to avoid updating unintended records

Answer №1

Looking at it from a database perspective, a relation is essentially a foreign key that points to a primary key. In this scenario, typeorm automatically creates a column called bulkOrderId in the orders table, linking it to the id column in the table associated with the BulkOrder entity.

If you need to eliminate this relationship, you can simply set the bulkOrderId column to null. A recommended approach to accomplish this is as follows:

@Entity({ name: 'orders' })
export class Order {
 ...

  @ManyToOne(() => BulkOrder, (bulkOrder) => bulkOrder.orders)
  @JoinColumn({ name: 'bulkOrderId' })
  bulkOrder?: BulkOrder;

  @Column({ name: 'bulkOrderId' })
  bulkOrderId?: string;
}
.createQueryBuilder()
.update(Order)
.set({ status: OrderStatus.OPEN, bulkOrderId: null }).
where(...).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

A guide on combining two native Record types in TypeScript

Is it possible to combine two predefined Record types in TypeScript? Consider the two Records below: var dictionary1 : Record<string, string []> ={ 'fruits' : ['apple','banana', 'cherry'], 'vegeta ...

The interface 'HTMLIonIconElement' is not able to extend both 'IonIcon' and 'HTMLStencilElement' types at the same time

After upgrading my Angular Ionic app to use Angular v13 from Angular 12 with the command ng update, I encountered errors preventing me from running the application successfully. [ng] Error: node_modules/ionicons/dist/types/components.d.ts:66:15 - error TS2 ...

The value stored within an object does not automatically refresh when using the useState hook

const increaseOffsetBy24 = () => { setHasMore(false); dispatch(contentList(paramsData)); setParamsData((prevState) => ({ ...prevState, offset: prevState.offset + 24, })); setHasMore(true); }; This function increment ...

Can you explain the distinction between `any[]` and `{ [s: string]: any }`?

I was attempting to make this code snippet function properly: test(a: any[]) { let b: string[][] = []; b.push(Object.keys(a[0])); b.push(...a.map(e => Object.values(e))); } However, the compiler is throwing an error for the b.push(...a.ma ...

Comparison of env.local and String variables

I encountered an access denied error with Firebase. The issue seems to arise when I try passing the value of the "project_ID" using an environment variable in the backend's "configs.ts" file, as shown in the code snippet below: import 'firebase/f ...

Utilizing CakePHP's DateTime with PHP's date() function

In my database, I have a field type called datetime in one table representing the start date and time of an event. I am looking to execute the following code: $taken_timeslots = $this->Schedule->find('all', array( 'conditions' ...

Leverage Ramda's clone function within a pipeline in a manner that ensures type safety

My goal is to utilize Ramda for cloning and updating objects in a type-safe manner, drawing inspiration from this approach. However, I am facing challenges implementing it in a type-safe way. Updating a nested object seems to work perfectly fine in a type ...

Tips for triggering an event from a function instead of the window

Everything is functioning as expected, with the event listener successfully capturing the custom event when it is dispatched from the window and listened for as loading, all seems to be working well. const MyLib = mylib(); function mylib() { const re ...

Challenges with React Event Listener Types

https://i.sstatic.net/cVlpr.png useEffect(() => { const handleEscClose = (e: KeyboardEvent) => { if (e.key === 'Escape') changeVisibility(); }; if (isVisible) document.addEventListener('keydown', handleEscClos ...

Is there a way for Ionic to remember the last page for a few seconds before session expiry?

I have set the token for my application to expire after 30 minutes, and I have configured the 401/403 error handling as follows: // Handling 401 or 403 error async unauthorisedError() { const alert = await this.alertController.create({ header: 'Ses ...

An asynchronous function operates incessantly

I have implemented the following code in React using hooks to fetch data from two different sources. const [ permissionTree, setPermissionTree ] = useState([]); const [ availablePermissionsInRole, setAvailablePermissionsInRole ] = useState<Permission[] ...

Exploring subobjects while fetching observables (typescript/angular)

When retrieving JSON from an API into an Angular service, I am working with a collection of objects structured like this: { "data": { "id": 1, "title": "one" }, "stats" : { "voteCount": 8 } } I am particularly interested in the ' ...

Purge the inversify-js container and fetch fresh service instances

My frontend application in react-native utilizes inversify-js for service classes. I have implemented an IOC structure where services are shared as singleton instances, each with an init/destroy method to manage internal state. While the init/destroy mec ...

Substitute all properties of a specific type with a predetermined value in Typescript using recursive substitution

If we consider the given type structure: type Person = { name: string age: number experience: { length: number title: string } } Can we create a type like this: type FieldsOfPerson = { name: true age: true experience: { length: t ...

Unable to modify the Express Request User type, however, I have the ability to incorporate new attributes to Request object

Encountering a familiar issue with what appears to be a simple fix. The Express Request object includes a user property that is specified as Express.User (an empty object). Attempting the common approach to redefining it: // index.d.ts import { User as P ...

`Unresponsiveness in updating bound property after change in Angular2 child property`

Having trouble with my custom directive and ngOnChanges() not firing when changing a child property of the input. my.component.ts import {Component} from 'angular2/core'; import {MyDirective} from './my.directive'; @Component({ d ...

Having trouble locating the Angular Material core theme within the asp.net core 2.0 template using Angular 5

CustomConfig.js const treeModules = [ '@angular/animations', '@angular/common', '@angular/compiler', '@angular/core', '@angular/forms', '@angular/http', '@angular ...

What is the reason behind having to coerce the enum value before the object type can be properly recognized?

My object is discriminated based on the type property, which can be any value from a specified enum. I encounter an issue in TypeScript when passing a valid object to a function; it complains about mismatched types. However, coercing the enum value resolve ...

Styling Form validation with Ant Design

Can a className prop be included in the Form.Item validation? <Form.Item name="username" rules={[ { required: true, message: '...' }, className="customValidation" //<- attempting to add a className but it is not fu ...

Set the value of HTML input type radio to a nested JSON string

Currently, I'm developing an Angular application and encountering an issue where I am unable to access the nested array value 'subOption.name' for the input type radio's value. I'm uncertain if the error lies within the metaData st ...