首页 > 解决方案 > TypeORM 使用 ManyToOne 字段和 String 字段创建唯一约束

问题描述

我有以下两个模型:

模型1.ts

@Entity()
export class Model1 {

  /**
   * Unique identifier
   */
  @PrimaryColumn()
  id: string = guid();


  /**
   * Label to use in the UI
   */
  @Column({
    nullable: true,
  })
  label?: string;

  @ManyToOne(type => Model2, model2 => model2.model1)
  model2: Model2;
}

模型2.ts

@Entity()
export class Model2 {

  @PrimaryColumn()
  id: string = guid();

  @Column()
  somename: string;

  @OneToMany(type => Model1, model1 => model1.model2, {
    cascade: true,
  })
  model1: Model1[];
}

鉴于以上两个实体,我想在 Model 1 表中以 (label, model2.id) 的形式创建一个唯一约束

我尝试搜索多个文档,但找不到解决方案。有没有办法可以使用 TypeORM 做到这一点?

标签: mysqlnode.jstypescripttypeorm

解决方案


推荐阅读