【问题标题】:Typeorm postgres: Create relation by unique column (not PK) as constraintTypeorm postgres:通过唯一列(不是PK)作为约束创建关系
【发布时间】:2021-07-07 21:12:03
【问题描述】:

所以我现在挣扎了一段时间。我正在尝试使用 typeorm 在 postgres 中为我的自定义连接表建模。

我想将非 PK 列 ('uuid') 设置为关系约束,但我找不到任何解决方案。

我有两个已经存在的表,我们将它们命名为 A 和 B。

@Entity()
export class A {
  @PrimaryGeneratedColumn('uuid')
  uuid: string;

 ...
}

@Entity()
@Unique(['uuid'])
export class B {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  @Generated('uuid')
  uuid: string;

 ...
}

所以现在我希望我的联接表是

@Entity()
@Unique(['a', 'b'])
export class AB {
  @PrimaryGeneratedColumn('uuid')
  uuid: string;

  @ManyToOne(() => A, { nullable: false })
  a: A;

  @ManyToOne(() => B, { nullable: false })
  b: B;
}

然后我想保存新实体,例如 repository.save({ a: { uuid: uuid }, b: { uuid: uuid }}); 当我尝试使用其 PK('id')保存关系 B 但不能使用 uuid 时,它可以工作。

如果有任何帮助,我将不胜感激 干杯

【问题讨论】:

    标签: javascript postgresql typeorm


    【解决方案1】:

    好的,我想通了,如果有人遇到同样的问题,这是我的解决方案。 我已经从表 B 中删除了 @Unique('uuid') 并直接在列上声明它,我还必须将列标记为类型:'uuid',然后在连接表上我使用了指向 uuid 列的 @JoinColumn 装饰器。

    @Entity()
    export class B {
      @PrimaryGeneratedColumn()
      id: number;
    
      @Column({ unique: true, type: 'uuid' })
      @Generated('uuid')
      uuid: string;
    
     ...
    }
    
    @Entity()
    @Unique(['a', 'b'])
    export class AB {
      @PrimaryGeneratedColumn('uuid')
      uuid: string;
    
      @ManyToOne(() => A, { nullable: false })
      a: A;
    
      @ManyToOne(() => B, { nullable: false })
      @JoinColumn({ referencedColumnName: 'uuid' })
      b: B;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-03-06
      • 2019-10-10
      • 1970-01-01
      • 2022-11-04
      • 1970-01-01
      • 2010-12-06
      • 2017-02-15
      • 1970-01-01
      • 2014-06-20
      相关资源
      最近更新 更多