Trouble arises when trying to save an Entity using CASCADE in a One-To-Many relationship

Similar to the inquiry posted by this user, I am facing a challenge while trying to persist an entity named Project along with its associated Spaces through a One-to-Many relationship using TypeORM. Although the SQL logging output indicates a successful commit:

query: START TRANSACTION
query: INSERT INTO "project_model"(...) VALUES (...) RETURNING "dateCreated", "dateModified"
query: UPDATE "space_model" SET "projectId" = ... WHERE "id" = ...
query: COMMIT

I cannot find the data in the Spaces table when checking Postgres.

Here are the two models involved:

@Entity()
class Project extends IProject {
    @OneToMany(type => Space, space => space.project)
    public spaces: Space[]
}
@Entity()
class Space extends ISpace {
    @ManyToOne(type => Project, (project) => project.spaces, {
    cascade: true
    })
    project: Project
}

In addition, here is the simplified repository method responsible for saving:

  async updateData(data: Partial<T>): Promise<T> {
    await this.getRepo();

    const dbObj = data as any;
    console.log(dbObj);
    const updated = await this.repo.save(dbObj);

    return updated;
  }

What could be causing this issue?

Answer №1

After a bit more digging, I finally managed to uncover the solution. It turns out that properly handling the cascade relationship is key, as highlighted in this helpful thread.

Note that the cascade option should be placed on the element responsible for saving data, not the potential saved element itself.

For instance, I made adjustments to Project like so:

@Entity()
class Project extends IProject {
   @OneToMany(type => SpaceModel, space => space.project, {cascade: true})
   spaces: Partial<SpaceModel>[];
}

Similarly, modifications were made to Space:

@Entity()
class Space extends ISpace {
  @ManyToOne(() => ProjectModel, 
    project => project.spaces, { 
      onDelete: 'CASCADE',
      onUpdate: 'CASCADE'
    }
  )
  @JoinColumn()
  project: ProjectModel;
}

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

exit out of React Dialog using a button

I have a scenario where I want to automatically open a dialog when the screen is visited, so I set the default state to true. To close the dialog, I created a custom button that, when clicked, should change the state to false. However, the dialog does no ...

Is the alias name absolute or converted to AliasId when establishing a connection with Sequelize and Migrations?

In my Housing model, I have a sequelize association set up like this: Housing.belongsTo(models.User, {as : Owner}); When adding the column to the model and Migrations file with this association, will the table be named "Owner" exactly as the Alias, or "Ow ...

Having Trouble with Ionic 2's Loading Controller

In my attempt to utilize the recently added LoadingController in this scenario: let loading=this.load.create({ content: "Connexion au serveur Migal en cours..." }); loading.present(); this.http.get(this.urlCheckerForm.value.migalUrl+'/action/Mobi ...

Issue encountered with asynchronous waiting while invoking a function

var value = await this.upload(); if (value == true) { // Update item properties this.item.photos = this.uploaded; this.item.price = null; this.item.qty = null; // Add item to data service this.dataSrv.addItem(this.item) .then(() => { ...

Incompatibility issues between NestJS and socket.io package

After diligently following the documentation, I attempted to install and work with socket.io on nestjs. However, I encountered multiple issues when installing packages. Despite trying different methods to update the package, nothing seemed to resolve the i ...

Best Practices for Variable Initialization in Stencil.js

Having just started working with Stencil, I find myself curious about the best practice for initializing variables. In my assessment, there seem to be three potential approaches: 1) @State() private page: Boolean = true; 2) constructor() { this.p ...

"What is the significance of the .default property in scss modules when used with typescript

When dealing with scss modules in a TypeScript environment, my modules are saved within a property named default. Button-styles.scss .button { background-color: black; } index.tsx import * as React from 'react'; import * as styles from ' ...

Migration in Sequelize always adds columns to the public schema

I am currently working on an Express application that uses Sequelize as the ORM and PostgreSQL as the database. The database is set up in a way where each tenant in the application has their own schema. In my migration files, I have included addColumn and ...

"I am looking for a way to incorporate animation into my Angular application when the data changes. Specifically, I am interested in adding animation effects to

Whenever I click on the left or right button, the data should come with animation. However, it did not work for me. I tried adding some void animation in Angular and placed a trigger on my HTML element. The animation worked when the page was refreshed, bu ...

The current date is indicating that the date string provided is invalid for interpretation by dayjs()

Have you tried using DayJs? If you're working on the browser, specifically with Firefox + Vue + typescript, here's my date string: 2021-02-05 12:00 AM However, when I include the AM/PM in the code like this: const dateObj: any = dayjs('2 ...

Issue with ngRX infinite loop caused by the updateOne function in the adapter

Hey there, I'm struggling to figure out why my code is stuck in an infinite loop. I've searched online extensively but haven't found a solution that fits my specific issue. This is the code snippet causing the problem: /** * CODE ...

The nest build process encounters errors related to TypeScript in the @nestjs/config package, causing it

Encountering several issues related to @nestjs/config, causing the npm build command to fail. However, npm run start:dev is still functional despite displaying errors. See below for screenshots of the errors and environment: https://i.sstatic.net/Wxkkn.png ...

The Vue Router hooks are not being activated within the component when utilizing Typescript

I've been pondering this issue for quite some time. Despite my extensive search efforts, I am still unable to figure out why the route-hooks are not working in my component: 1. The component is being loaded from RouterView: <router-view class="z1 ...

Potentially null object is present in a callback

The code I have is as follows: let ctx = ref.current.getContext("2d"); if(ctx){ ctx.lineWidth=1; // this line executes without errors ctx.strokeStyle=props.barStroke??"darkgray";// this line execut ...

Displaying hidden Divs in React Typescript that are currently not visible

I have an array with various titles ranging from Title1 to Title8. When these titles are not empty, I am able to display their corresponding information successfully. Now, my goal is to include a button that will allow me to show all fields. For example, ...

Incorrect Column Header Display in React with Kendo-UI Grid

I have a React application using redux as state manager. In this application we are deciding to use Kendo Ui grids. The first test is Ok but we noticed that the columns are totally wrong. We define only 5 Columns to be displayed in the table but we noticed ...

Can you identify the difference between `{x?: boolean}` and `{x: boolean|undefined}`?

This scenario applies to both scenarioOne and scenarioTwo: type OptionalType = {y?: boolean}; const scenarioOne: OptionalType = { y: undefined }; const scenarioTwo: OptionalType = { }; I am seeking a solution where only scenarioTwo would pass the type ch ...

Issues with running NPM script for compiling TypeScript code

[UPDATE] Initially, I resolved this issue by uninstalling tsc using npm uninstall tsc (as recommended in the response marked as the answer). However, the problem resurfaced after some time, and eventually, I found success by utilizing Windows Server for L ...

Generating JavaScript files automatically upon initiating the npm start command

As I develop an Angular2 app with typescript, I encounter a situation where running npm start results in all .ts files being compiled into javascript files and saved in the directory. Is there a way to disable this automatic compilation? The contents of m ...

The parameters in VueJS are malfunctioning on this webpage

I created my vue in an external file and included it at the bottom of my webpage, but I am encountering issues with its functionality. One specific problem arises when using v-model, resulting in a template error displayed on the page: Error compiling t ...