Difficulties inserting entity in relationship between each others #1989
Answered
by
B4nan
marc-andre-julien-uqam
asked this question in
Q&A
-
I am new to MikroOrm and I am having difficulties to insert element that are relationship to each other. I am pretty sure I am just doing it wrong. Here a exemple of how I am trying to do it. Mikro does not seem set the fk in the table dec_declinaison. Anyone have an idea what is the problem? /* 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
*/ |
Beta Was this translation helpful? Give feedback.
Answered by
B4nan
Jun 30, 2021
Replies: 1 comment
-
This is actually a bug, the problem is with mapping back the PK when it is not called |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
marc-andre-julien-uqam
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is actually a bug, the problem is with mapping back the PK when it is not called
id
, and it will be postgres specific. The value is mapped as a regular field and not as a primary key, therefore the propagation to owning side (m:1) does not work.