What is the process for adding connected entities in MikroORM?

I am encountering difficulties in inserting related elements into each other. I believe I may be approaching it incorrectly. Here is an example of how I am attempting to do so. Mikro does not appear to set the foreign key in the dec_declinaison table.

/* Schema
CREATE TABLE prog.prc_programme_code (
    prc_id serial NOT NULL,
    CONSTRAINT i_prc_pk PRIMARY KEY (prc_id),
);
CREATE TABLE prog.dec_declinaison (
    dec_id serial NOT NULL,
    prc_id int4 NOT NULL,
    CONSTRAINT i_dec_pk PRIMARY KEY (dec_id),
);
*/
import { Collection, Entity, ManyToOne, MikroORM, OneToMany, PrimaryKey } from '@mikro-orm/core';
import * as dotenv from 'dotenv';
dotenv.config();

@Entity({ collection: 'prog.prc_programme_code' })
class Programme {
  @PrimaryKey({ fieldName: 'prc_id' })
  id!: number;
  @OneToMany(() => Declinaison, (declinaison) => declinaison.programme)
  declinaison = new Collection<Declinaison>(this);
}

@Entity({ collection: 'prog.dec_declinaison' })
class Declinaison {
  @PrimaryKey({ fieldName: 'dec_id' })
  id!: string;
  @ManyToOne({ entity: () => Programme, fieldName: 'prc_id' })
  programme!: Programme;
}

(async () => {
  const orm = await MikroORM.init({
    debug: true,
    discovery: { warnWhenNoEntities: false },
    entities: [Programme, Declinaison],
    type: 'postgresql',
  });
  const programme = new Programme();
  const declinaison = new Declinaison();
  programme.declinaison.add(declinaison);
  await orm.em.persistAndFlush(programme);
})();

/* Result
[query] begin
[query] insert into "prog"."prc_programme_code" default values returning "prc_id" [took 8 ms]
[query] insert into "prog"."dec_declinaison" ("prc_id") values (NULL) returning "dec_id" [took 4 ms]
[query] rollback
(node:32404) UnhandledPromiseRejectionWarning: NotNullConstraintViolationException: 
insert into "prog"."dec_declinaison" ("prc_id") values (NULL) returning "dec_id" - 
null value in column "prc_id" of relation "dec_declinaison" violates not-null constraint
*/

Answer №1

The provided code snippet failed to execute due to a bug present in the library. The problem has been identified and fixed with the latest commit. For additional information, refer to the related GitHub issue linked below.

https://github.com/mikro-orm/mikro-orm/issues/1990

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

Angular component.html does not compile due to a check that includes inline array creation

There is an enum called Status: export enum Status { SOME_VAL = "SOME_VAL", SOME_VAL_2 = "SOME_VAL_2", SOME_VAL_3 = "SOME_VAL_3"; } Also, I have an interface named SomeInterface: export SomeInterface { status? ...

The movement of particles in tsparticles experiences interruptions when built in React, causing defects in their motion or noticeable stutter and lag

The performance is flawless in development mode with npm run start, but once deployed and running the production build (npm run build), there seems to be a disturbance in particle movement or a drastic decrease in speed. Despite experimenting with all ava ...

Utilizing v-for in Vue with TypeScript to generate multiple checkboxes

My goal was to capture the values of checkboxes and store them in an array using v-model. However, I encountered an issue where the first time I toggle a checkbox, it doesn't register. Only after checking a second box and hitting submit does the secon ...

Intercept Axios Responses - Retrieving API Responses for HTTP Statuses that are not in the 200 range

I've set up a custom Axios instance with interceptors for handling responses. As per the Axios documentation, the success interceptor is triggered for 2xx statuses while the error interceptor handles any other status codes. My goal is to show an error ...

Could someone clarify for me why I am unable to view the connection status within this code?

Having trouble with the Ionic Network plugin. I've included this code snippet, but it's not functioning as expected. No console logs or error messages are showing up. import { Network } from '@ionic-native/network'; ionViewDidLoad() { ...

Is it necessary to upload the node_modules folder to Bitbucket?

When uploading an Angular 2 app to Bitbucket, is it necessary to include the node_modules and typings folders? I am planning to deploy the app on Azure. Based on my research from different sources, it seems that when deploying on Azure, it automatically ...

ways to coordinate two subscriptions so that one initiates only when the other one emits

Currently, I am developing an Angular application with a specific scenario. I have an observable signal named dataFetchedEvent$, which indicates that data has been fetched from a remote location. Additionally, there is a form that relies on this remote dat ...

Add a service to populate the values in the environment.ts configuration file

My angular service is called clientAppSettings.service.ts. It retrieves configuration values from a json file on the backend named appsettings.json. I need to inject this angular service in order to populate the values in the environment.ts file. Specific ...

Modifying the form-data key for file uploads in ng2-file-upload

I have implemented the following code for file upload in Angular 2+: upload() { let inputEl: HTMLInputElement = this.inputEl.nativeElement; let fileCount: number = inputEl.files.length; let formData = new FormData(); if (fileCount > 0) { // a f ...

What is the error message "Cannot assign type 'IArguments' to argument"?

Currently employing a workaround that is unfortunately necessary. I have to suppress specific console errors that are essentially harmless. export const removeConsoleErrors = () => { const cloneConsoleError = console.error; const suppressedWarnings ...

Consecutive API requests within React context

When I'm developing locally, I encounter the error message Error: Rendered more hooks than during the previous render. in my application when refreshing the page. I suspect this is happening because I am making two calls within my provider. The first ...

Can inner function calls be mimicked?

Consider this scenario where a module is defined as follows: // utils.ts function innerFunction() { return 28; } function testing() { return innerFunction(); } export {testing} To write a unit test for the testing function and mock the return value ...

Getter and setter methods in Angular Typescript are returning undefined values

I am facing a challenge in my Angular project where I need a property within a class to return specific fields in an object. Although I have implemented this successfully in .Net before, I am encountering an issue with getting an "Undefined" value returned ...

Identify and handle errors effectively using TypeScript

I have a question regarding my Express server setup. Here is the code snippet: import express from "express"; import helmet from "helmet"; import cors from "cors"; const app = express(); app.use(helmet()); app.use(cors()); a ...

How can I make sure that my function returns a mutated object that is an instance of the same class in

export const FilterUndefined = <T extends object>(obj: T): T => { return Object.entries(obj).reduce((acc, [key, value]) => { return value ? { ...acc, [key]: value } : acc; }, {}) as T; }; During a database migration process, I encounte ...

Customize your Loopback 4 OpenAPI with NSWAG by making filters optional and specifying data types

I am encountering an issue with the Loopback 4 filter on the generated endpoints being marked as required in my Nswag typescript file. I need it to be optional, but I am struggling to locate where this requirement is originating from. The endpoint from my ...

Debugging Typescript code with line numbers

When opening the console in a browser, typically the javascript line number of a function call or error message is displayed. However, my current setup involves using TypeScript, which gets compiled to Javascript. I am wondering if there is a way to retr ...

Applying background-image in ngStyle results in an undefined value

I have been attempting to incorporate images (retrieved through an API) as the background-image of an element. However, I keep encountering the error message Cannot read property 'url' of undefined, even though the URL is actually being rendered. ...

Implementing a props interface for conditions in styled components within a React application using Typescript

This specific component is created using React along with the "styled components" library to manage user input. In the case of invalid user input, the corresponding styles should be displayed as shown below (class invalid). Although this example functions ...

Typesafe-actions for defining typings of async actions reducers

I'm currently facing a minor issue while using createAsyncAction from the library typesafe-actions (Typesafe Actions) and correctly typing them for my reducer function Below is an example of the action being created: export const login = createAsync ...