相互に関連する要素を挿入するのが困難です。私はそれを間違っているだけだと確信しています。これが私がそれをやろうとしている方法の例です。Mikro はテーブル dec_declinaison に fk を設定していないようです。
/* 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
*/