【问题标题】:typeorm relation in embedded column嵌入列中的 typeorm 关系
【发布时间】:2022-11-15 16:48:01
【问题描述】:

我正在使用 NestJs、Typeorm 和 Postgresql。

我正在尝试在嵌入式实体中使用 ManyToOne 关系。我需要在节点环境中加载外键列,所以添加了一个额外的列(下面的createdById列)。这就产生了问题。

这是我的代码。

A.ts

@Entity()
export class A {
    @PrimaryGeneratedColumn()
    id!: number;

    @Column(() => Embed, { prefix: false })
    embed!: Embed;

    @CreateDateColumn({ name: 'created_at' })
    createdAt!: Date;
}

嵌入.ts

export class Embed {
    @Column()
    x!: number;

    @Column()
    y!: number;

    @ManyToOne(() => B)
    @JoinColumn({ name: 'created_by_id' })
    createdBy?: B;

    @Column({ name: 'created_by_id' })
    createdById!: number;
}

B.ts

@Entity()
export class B {
    @PrimaryGeneratedColumn()
    id!: number;

    @CreateDateColumn({ name: 'created_at' })
    createdAt!: Date;
}

当我使用选项TYPEORM_SYNCHRONIZE=trueTYPEORM_LOGGING=true 运行应用程序时,我收到query failed: CREATE TABLE "a" ("id" SERIAL NOT NULL, "created_at" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(), "created_by_id" integer NOT NULL, "created_by_id" integer NOT NULL, "x" integer NOT NULL, "y" integer NOT NULL, CONSTRAINT "PK_684f21444e543375e4c2e6f27fe" PRIMARY KEY ("id"))Message: column \"created_by_id\" specified more than once. 之类的错误消息。 Typeorm 尝试创建 created_by_id 列两次。 (我应用了自定义 NamingStrategy 以便嵌入实体名称的列是蛇形大小写)

如果我将createdBycreatedById 列直接放置到A,则不会出错。是typeorm版本的问题吗?还是有其他解决方案?

包版本:

"dependencies": {
    "@nestjs/typeorm": "7.1.0,
    "typeorm": "0.2.31",
}

使用 docker 容器运行,

node image: 16.14.2-alpine3.15,
postgres image: mdillon/postgis:11-alpine

【问题讨论】:

    标签: postgresql nestjs typeorm node.js-typeorm


    【解决方案1】:

    TypeORM 文档说你不需要用@Entity() 装饰嵌入类。

    参见https://orkhan.gitbook.io/typeorm/docs/embedded-entities 中的Name

    【讨论】:

    • 感谢您的回答!实际上,我没有将 @Entity() 装饰器放在 Embed 类上。我会编辑这个问题,
    猜你喜欢
    • 2020-10-10
    • 2022-07-12
    • 2021-01-05
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 2020-10-18
    相关资源
    最近更新 更多