首页 > 解决方案 > 如何在 TypeORM 中使用可为空字段创建唯一约束?

问题描述

如何在 TypeORM 中使用可为空字段创建唯一约束?

我使用了 postgresql12,节点 v12.22.7。

创建单独的原始查询会更好吗?

没有迁移工具?

如果我使用原始查询,我可以像下面的地址一样使用它吗?

如何使用可为空的列创建复合 UNIQUE 约束?

这是我的代码示例。

@Entity('users')
@Unique('username-unique',['username', 'deletedAt'])
export class User {
  @PrimaryGeneratedColumn()
  id: number

  @Column({ length: 100 })
  username: string

  @Column({ length: 100 })
  name: string

  // sha256
  @Exclude()
  @Column({ type: 'bytea', select: false})
  password: Buffer

  @Column({
    nullable: true,
    type: 'timestamp with time zone'
  })
  lastLoginAt: Date | null

  @OneToMany(() => RoleBindingEntity, (roleBinding) => roleBinding.user, { cascade: true })
  @JoinColumn()
  roleBinding: RoleBindingEntity[]

  @CreateDateColumn({
    type: 'timestamp with time zone',
    default: () => 'CURRENT_TIMESTAMP'
  })
  createdAt: Date

  @UpdateDateColumn({
    type: 'timestamp with time zone',
    default: () => 'CURRENT_TIMESTAMP'
  })
  updatedAt: Date

  @DeleteDateColumn({
    type: 'timestamp with time zone'
    nullable: true,
  })
  deletedAt: Date
}

标签: typeorm

解决方案


推荐阅读