The solution to automatically delete orphaned rows in TypeORM

Having a one-to-many relationship in TypeORM, I am interested in deleting rows from the many side of the connection rather than just unlinking them and leaving orphaned entries. Can anyone suggest a way to achieve this since the proposed feature for it was rejected? Any workarounds or alternative methods would be greatly appreciated. Here's a simplified code snippet for reference:

@Entity()
@TableInheritance({ column: { name: 'type', type: 'text' } })
export default class Geolocation {
  @PrimaryGeneratedColumn()
  id!: number;

  @IsGeoJSONPoint
  @Column('geography')
  point!: Point;
}


@ChildEntity('offer')
export default class OfferGeolocation extends Geolocation {
  @ManyToOne(type => Offer, offer => offer.geolocations, { onDelete: 'CASCADE' })
  offer!: Offer;
}


@ChildEntity('business')
export default class BusinessGeolocation extends Geolocation {
  @ManyToOne(type => Business, business => business.geolocations, { onDelete: 'CASCADE' })
  business!: Business;
}


@Entity()
export default class Business {
  @PrimaryGeneratedColumn()
  id!: number;

  // To remove orphaned business geolocations
  @OneToMany(type => BusinessGeolocation, businessGeolocation => businessGeolocation.business, { cascade: true })
  geolocations!: BusinessGeolocation[];
}


@Entity()
export default class Offer {
  @PrimaryGeneratedColumn()
  id!: number;

  // To remove orphaned offer geolocations as well
  @OneToMany(type => OfferGeolocation, offerGeolocation => offerGeolocation.offer, { cascade: true })
  geolocations!: OfferGeolocation[];
}

Answer №1

A recent PR was successfully merged on January 12, 2021, addressing this issue.

This enhancement has been included in TypeORM's version 0.2.30:

0.2.30 (2021-01-12)

Features

  • relations: Orphaned row action (#7105) (efc2837)

To implement the desired functionality, consider the following code snippet:

@ChildEntity('business')
export default class BusinessGeolocation extends Geolocation {
  @ManyToOne(
    type => Business, business => business.geolocations, {
      onDelete: 'CASCADE',
      orphanedRowAction: "delete" // NEW
    })
  business!: Business;
}

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

How to retrieve a random element from an array within a for loop using Angular 2

I'm in the process of developing a soundboard that will play a random sound each time a button is clicked. To achieve this, I have created an array within a for loop to extract the links to mp3 files (filename), and when a user clicks the button, the ...

The yarn/npm package manager seems to be utilizing outdated code in an inexplicable way when paired with mocha and typescript

I recently encountered a strange issue that has left me scratching my head. When I manually run my test command, I receive two test results. However, when I execute the same command in a yarn/npm script, only one result is displayed. Has anyone else experi ...

What is the significance of having both nulls in vue's ref<HTMLButtonElement | null>(null)?

Can you explain the significance of these null values in a vue ref? const submitButton = ref<HTMLButtonElement | null>(null); ...

What methods are available to expedite webpack compilation (or decouple it from server restart)?

My current setup includes the following configurations: import path from 'path' import type {Configuration} from 'webpack' const config: Configuration = { mode: 'development', entry: path.join(__dirname, '../..&apos ...

Ways to manage drag and drop functionality within Cypress when traditional Cypress techniques are not effective

I need help with the drag and drop function in Cypress. I have tried three different methods but none of them seem to work. I have included my code below, which is not functioning as expected. Does anyone have any suggestions on what might work better in t ...

Utilizing Angular2 with Webpack in Visual Studio 2015

Is there a way to utilize Visual Studio 2015 alongside Webpack and Angular2? I have successfully created an Angular2 App with VS, but now that I've added Webpack to build my app, I would like to debug all of my code using IIS Express. I want to be abl ...

Utilize knex.js and TypeScript to create queries with specific conditions

I am trying to create a dynamic query that will include a where clause based on whether the variables name and/or city are passed. While I couldn't find a specific method for this in the documentation, I attempted to add the where clauses directly to ...

Error: The program encountered a type error while trying to access the '0' property of an undefined or null reference

I am a beginner in the world of coding and I am currently working on creating an application that allows users to add items to their order. My goal is to have the quantity of an item increase when it is selected multiple times, rather than listing the same ...

Using the useContext hook in a TypeScript class component: a step-by-step guide

I am working with a TypeScript class component and have successfully created a context that can be accessed globally. I am interested in learning how to implement this context in a .ts class component and if it is possible to use it in a pure TypeScript ...

The Order ID field in the Serenity-Platform's Order Details tab is not registering orders

I've been working on replicating the functionality of Orders-Order detail in my own project. https://i.stack.imgur.com/Bt47B.png My custom module is called Contract and Contract Line item, which I'm using to achieve this. https://i.stack.imgur ...

Creating a new TypeScript file via the command line: A step-by-step guide!

When I want to create a new file named main.ts, I try to write the command but it keeps showing an error. "bash: code: command not found" https://i.stack.imgur.com/cpDy3.png ...

Steps to resolve the 'Cannot assign value to userInfo$ property of [object Object] that only has getter' issue in Angular

I am currently in the process of building a web application using NGXS, and I'm encountering a specific error that I'm trying to troubleshoot. The issue arises when I attempt to fetch data from an API and display it within a column on the page. D ...

React throwing a typescript error while attempting to update state based on the previous state

Hello there! I'm fairly new to working with TypeScript and I've encountered an issue with a piece of state in a child component. I'm trying to modify it based on the previous value, but every time I call the setState function, I get a type e ...

The package import path varies between dynamic code generation and static code generation

I have organized the src directory of my project in the following structure: . ├── config.ts ├── protos │ ├── index.proto │ ├── index.ts │ ├── share │ │ ├── topic.proto │ │ ├── topic_pb. ...

Creating a return type in TypeScript for a React Higher Order Component that is compatible with a

Currently utilizing React Native paired with TypeScript. Developed a HOC that functions as a decorator to add a badge to components: import React, { Component, ComponentClass, ReactNode } from "react"; import { Badge, BadgeProps } from "../Badge"; functi ...

The dropdown navigation bar fails to close upon being clicked

I'm currently facing an issue with the navbar in my project. The bootstrap navbar doesn't close automatically after clicking on a link. I have to move my mouse away from the navbar for it to close, which is not ideal. Additionally, I'm worki ...

Is it possible to define a namespaced external module in TypeScript?

Currently, I am dealing with some legacy js modules that are either namespaced on window or define'd if the page is using AMD. Here's an example: // foo/bar.js (function (root, factory) { if (typeof define === "function" && define.am ...

Explain to me the process of passing functions in TypeScript

class Testing { number = 0; t3: T3; constructor() { this.t3 = new T3(this.output); } output() { console.log(this.number); } } class T3 { constructor(private output: any) { } printOutput() { ...

Tips on getting the dropdown value to show up on the header when it changes using Angular 2 and TypeScript

I need assistance with creating a dropdown field in Angular2. When the user selects "car", I want it to display beside the heading. Can anyone provide guidance on how to achieve this? HTML: <h1>Heading <span *ngFor= "let apps of apps">({{apps ...

Can we limit the return type of arrow function parameters in TypeScript?

Within my typescript code, there is a function that takes in two parameters: a configuration object and a function: function executeMaybe<Input, Output> ( config: { percent: number }, fn: (i: Input) => Output ): (i: Input) => Output | &apos ...