【问题标题】:TypeORM: What's difference between @Unique decorator and { unique: true } in column options?TypeORM:@Unique 装饰器和列选项中的 { unique: true } 有什么区别?
【发布时间】:2021-10-27 20:57:26
【问题描述】:

在 TypeORM 中,您可以在列选项中设置唯一标志,或将列设置为实体的唯一。

你什么时候用哪个,有什么区别?

@Unique(["firstName"])

https://typeorm.io/#/decorator-reference/unique

@Column({ unique: true })
firstName: string;

https://typeorm.io/#/decorator-reference/column

【问题讨论】:

  • 还有@Index({ unique: true })

标签: typeorm


【解决方案1】:

如文档中所述,@Unique 只能应用于整个实体,而不是单个列。为了可读性,我更喜欢简单的约束@Column({ unique: true }),因为它位于受影响的变量名称之上。

@Unique 语法的另一个优点是多列约束能力。您可以将多个列定义为一个唯一约束:@Unique(["firstName", "secondName"])@Column 装饰器无法做到这一点。

最后,您可以在使用@Unique 装饰器时为特定约束设置名称。以下单列约束定义在功能上是相同的,除了 @Unique 设置了一个人类可读的名称(注意:@Unique 需要实体变量字段名称,而不是实际的数据库列名称):

@Unique('my_unique_constraint', ['firstName'])  // make firstName unique
export class PersonEntity {

   @Column({ unique: true })   // make firstName unique, too; decide which to chose
   firstName: string;
...

【讨论】:

    猜你喜欢
    • 2012-03-01
    • 2023-03-16
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 2012-11-20
    • 2014-12-07
    • 2020-02-21
    • 1970-01-01
    相关资源
    最近更新 更多