如何在 TypeORM 中创建具有可为空字段的唯一约束?
我使用的是postgresql12,节点v12.22.7。
创建单独的原始查询是否更好?
没有迁移工具?
如果我使用原始查询,我可以像下面的地址一样使用它吗?
这是我的代码示例。
@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
}
// Remove unique: true from @Column and use @Index instead:
@Index({ unique: true, where: "externalId IS NOT NULL" })
来自 https://github.com/typeorm/typeorm/issues/4859#issuecomment-538583608
您可以将可空字段设置为唯一
@Column({ nullable: true, unique: true })
checking_data: string;
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "file_store" ADD "checking_data" character varying`);
await queryRunner.query(`ALTER TABLE "file_store" ADD CONSTRAINT "UQ_ab4f7e345fd08fb9611479b4cee" UNIQUE ("checking_data")`);
}