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
*/