为一对一关系创建主键

juz*_*ode 4 nest typeorm

背景:

由于任何唯一实体数据都是表的候选键,因此受约束的任何数据列unique都是候选键。将外键约束为唯一键和主键的语法是什么?例如我有实体:

@Entity()
export class A extends BaseEntity {
  PrimaryColumn()
  id: number;
}  
  
@Entity()
export class B extends BaseEntity() {
  @OneToOne(() => A) <---- need to set this foreign key unique and the primary key of B
  @JoinColumn()
  a: A;
}  
  
Run Code Online (Sandbox Code Playgroud)

如上所述,我希望外键是唯一的并且主键是 B。

到目前为止我尝试过的:

我以为我已经找到了解决方案,但这种语法似乎已经过时了;RelationOptions不包含以下primary属性:

@OneToOne( type => A, {primary: true})
@JoinColumn()
a: A
Run Code Online (Sandbox Code Playgroud)

另外,似乎确实可以使用 @Unique 装饰器将列标记为唯一,但是,我想知道在这种情况下是否有更好的方法来使列唯一。

lin*_*usw 9

请注意此处的更改: Typeorm 更改日志

主关系(例如 @ManyToOne(() => User, { Primary: true }) user: User)支持已删除。您仍然可以使用外键作为主键,但是现在您必须显式定义标记为主键的列。

之前的例子:

@ManyToOne(() => User, { primary: true })
user: User
Run Code Online (Sandbox Code Playgroud)

现在:

@PrimaryColumn()
userId: number

@ManyToOne(() => User)
user: User
Run Code Online (Sandbox Code Playgroud)

主列名称必须与相关实体上的关系名称 + 连接列名称匹配。如果关联实体有多个主键,并且想要指向多个主键,可以用同样的方式定义多个主列:

@PrimaryColumn()
userFirstName: string

@PrimaryColumn()
userLastName: string

@ManyToOne(() => User)
user: User
Run Code Online (Sandbox Code Playgroud)