The relationship between MikroORM and its parent entity

Greetings, I am currently working on a specific relationship:

https://i.sstatic.net/WTKeO.png

When trying to represent the parent's relationship in my entity, this is what I have:

@Entity({ tableName: 'product_instances' })
export class ProductInstance {
  @PrimaryKey()
  public readonly serial_number: string;
  @Property()
  public patrimony_code?: string;
  @Enum()
  public type: ProductTypes;
  @ManyToOne(() => Product, { fieldName: 'product_id' })
  public product: Product;
  @ManyToOne(() => Contract, { fieldName: 'contract_id' })
  public contract: Contract;
  @ManyToOne(() => Employee, { fieldName: 'employee_id' })
  public employee: Employee;
  @OneToMany({
    entity: () => ProductInstance,
    mappedBy: 'parent',
    orphanRemoval: true,
  })
  public parent = new Collection<ProductInstance>(this);
  @Property()
  public created_at = new Date();
  @Property({ onUpdate: () => new Date() })
  public updated_at = new Date();
  @Property()
  public deleted_at?: Date;

  constructor(container: instanceContainer) {
    this.serial_number = container.serial_number;
    this.patrimony_code = container.patrimony_code;
    this.type = ProductTypes[container.type];
    this.employee = container.employee;
    this.contract = container.contract;
    this.product = container.product;
  }

  static build = (container: instanceContainer): ProductInstance => {
    return new ProductInstance(container);
  };
}

However, I encountered an error related to the one-to-many relationship:

Both ProductInstance.parent and ProductInstance.parent are defined as owning sides, use 'mappedBy' on one of them

Do you think I should establish both a one-to-many and a many-to-one relationship?

Answer №1

You have implemented a new OneToMany relationship for the parent-child relationship. This means that you are defining parent as a list of parents.

In addition, you are setting parent as the reverse relationship key.

To optimize this setup, consider making the following changes:

  @ManyToOne({
    entity: () => ProductInstance,
    mappedBy: 'children',
  })
  public parent: ProductInstance;

  @OneToMany({
    entity: () => ProductInstance,
    mappedBy: 'parent',
  })
  public children = new Collection<ProductInstance>(this);

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 problem with the Custom Select Component: Error Arises When Utilizing the Generic Type <T,> with a Comma as Opposed to <T> Without a Comma

I recently developed a unique custom select component that extends the standard HTML select element. During the process, I made use of a generic type to accommodate a wide range of data types, but encountered an unexpected error. The issue seems to persist ...

Struggling with setting up Role-Based Access Control (RBAC) with cookie authentication in React

I've been working on incorporating Role Based Access Control into a React app using cookies, but I'm struggling to understand its use. The idea was to create a context that retrieves the data stored in the cookie through a specific API endpoint d ...

Comparing Passing Props with Extracting Cache in Apollo Client for Next.js applications

Hello there! I am diving into the world of apollo and graphql, specifically interested in SSR/SSG. While I have a basic understanding of what SSR/SSG entails, implementing it with apollo-client is a bit tricky for me. After some extensive searching online ...

Sending selected IDs from the JSON data

In my project, there is a JSON file named "workers" which contains information about all the workers. I have created a select component to display the names of the workers like this: https://i.sstatic.net/0Glyf.png Currently, I am selecting some workers ...

Mastering the art of typing queries in ReactQuery with Typescript

Hey there, can someone help me with this TypeScript error? https://i.sstatic.net/4Zn39.png https://i.sstatic.net/NTxAa.png https://i.sstatic.net/fiN87.png https://i.sstatic.net/CTd4u.png ...

Guide on Linking a Variable to $scope in Angular 2

Struggling to find up-to-date Angular 2 syntax is a challenge. So, how can we properly connect variables (whether simple or objects) in Angular now that the concept of controller $scope has evolved? import {Component} from '@angular/core' @Comp ...

Guide to declaring a dynamic type variable based on a constructor parameter

Consider the following class structure: class DataExtractor<T, K extends keyof T> { constructor(private data: T, private property: K) { } extractData(): T[K] { return this.data[this.property]; } } This approach may seem awkward ...

Is there a way to specify this component without it being nested within the parent element?

So I have this component nested within another one const selectColumn = useMemo<ColumnDef<Person>[]>( () => [ { id: "select", header: ({ table }) => ( <IndeterminateCheckbox {.. ...

Is it possible to utilize the System.import or import() function for any JavaScript file, or is it restricted to single module-specific files?

After reading an intriguing article about the concept of dynamic component loading: I am interested in learning more about the use of System.import. The author demonstrates a specific syntax for loading the JavaScript file of the module that needs to be d ...

Employing async/await for efficient data retrieval

Attempting to utilize async-await in TypeScript Vue 3 to retrieve data, but encountering an issue where the function is already logging 'undefined' (or executing before the function call) private async exportDataOrder() { await this.getDataEx ...

When the user clicks on a specific element, ensure that it is the main focus and generate an overlay

One of my challenges is implementing a custom element that captures user input upon clicking, focusing on it and overlaying other elements. I want the overlay to disappear if the user clicks outside the div. I attempted to achieve this using the iron-over ...

Discover the process of translating words within app.routing.module.ts in Angular

Having some trouble with my Angular routing module and ngx-translate languages. I'm trying to retrieve words from the languages in this module, but the code I've attempted isn't working: import { NgModule } from '@angular/core'; im ...

Issue with service injection within a singleton service in Angular2

Currently, I have two services in my application. ServiceA is non-singleton and provided to components through the Providers array, while ServiceB is a singleton that is listed in its module's Providers array. Both services work perfectly fine indepen ...

How is it possible for Typescript to let me create an object without explicitly defining all mandatory fields?

After creating a class and instantiating an object from it through the constructor, I expected to receive an error message indicating missing properties. However, despite the fact that the class description specified required fields, I was able to create a ...

Adjust the color of the IText element on a Fabric.JS canvas (utilizing React and typescript)

I have an input with the type=color attribute positioned outside of a Canvas. Inside the canvas, there are one or more IText objects along with other elements. My goal is to "change the color of selected text objects when the input value changes". Incorpo ...

Navigating through code in a monorepo using VSCode, Lerna, and Typescript

We maintain all of our Javascript related SDKs in a monorepo at Sentry. https://github.com/getsentry/sentry-javascript If you decide to clone this repository, make sure to properly set it up by running yarn install and then navigate to any file such as p ...

Unable to access or modify properties within a function passed as an argument

deleteDialog(item, func: Function) { this.dialogService .open(ConfirmDialogComponent, { context: { title:"Are you sure?", cancelClss: "info", confirmClss: "danger", }, ...

Having trouble resolving all parameters for the SiteNotificationComponent: (?)

I encountered an issue while attempting to append a component to the DOM. The error message displayed was "Can't resolve all parameters for SiteNotificationComponent: (?).at syntaxError." My goal was to insert HTML content by invoking showNotificatio ...

Using a predefined list of text entries, deduce a type or structure that accurately defines the dictionary, utilizing string literals to represent the various values within

My scenario involves a static dictionary: const myDict = { 1: "one", 2: "two" } The default inferred type in this case is Record<1 | 2, string>. I am seeking to create a type that exclusively accepts the exact string literal ...

Unusual deconstructing assignment leading to an undefined result

const apiConfig = JSON.parse(process.env.apiConfig); const securityContextConfigurations = _.get( apiConfig, 'agpAPIs', {}); // What exactly is happening here? const { securityContext : { apiKey, securityType } } = securityContextConfig ...