如何在 MikroORM 中插入相关实体?

How to insert related entities in MikroORM?

我很难插入相互关联的元素。我很确定我只是做错了。这是我如何尝试做的一个例子。 Mikro 似乎没有在 table 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
*/

上面的代码示例无法运行,因为库中存在错误。已提交修复。有关详细信息,请参阅下面的 GitHub 问题。

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