You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeORM中定义复合主键的列顺序?

在TypeORM中设置复合主键的顺序

要让实体生成PRIMARY KEY (date,id)的复合主键,核心是调整实体中主键列的声明顺序,同时统一主键字段的注解方式,具体修改如下:

修改后的实体代码

import { Entity, Column, Index } from "typeorm";
import { CreateDateColumn, UpdateDateColumn, DeleteDateColumn } from "../decorators/timestamps";

@Entity()
@Index("indx_popularity", ["date", "score", "entity_type"], { unique: false })
@Index("indx_id", ["id"], { unique: true })
export class EntityScore {
    // 将date主键列移至最前,确保主键顺序优先
    @Column({ primary: true, type: "date" })
    date: Date;

    // 替换@PrimaryGeneratedColumn为显式声明主键+自增的@Column
    @Column({ primary: true, generated: 'increment', type: 'int' })
    id: number;

    @Column({ length: 36 })
    entity_id: string;

    @Column({ length: 36 })
    entity_type: string;

    @Column({ type: "decimal", precision: 4, scale: 3 })
    score: number;

    @Column({ type: "json", nullable: true })
    raw: {};

    @CreateDateColumn({})
    created_at: string;

    @UpdateDateColumn({})
    updated_at: string;

    @DeleteDateColumn({})
    deleted_at: string;
}

原理说明

  • TypeORM生成复合主键时,完全按照实体中列的声明顺序排列主键字段,因此把date列放在id列之前,就能让它成为复合主键的第一个字段。
  • @PrimaryGeneratedColumn是primary: true+generated: 'increment'的语法糖,替换为@Column显式声明这两个属性,既保留了id的自增特性,又能和date共同组成复合主键,且顺序由列的声明位置决定。

修改后开启synchronize: true,TypeORM会自动生成PRIMARY KEY (date,id)的主键定义,无需手动修改迁移文件。

内容的提问来源于stack exchange,提问作者Kay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 13:32:25