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

问题描述

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

解决方法

上面的代码示例不起作用,因为库中存在错误。修复已经提交。有关更多详细信息,请参阅下面的 GitHub 问题。

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