TypeORM: What’s difference between @Unique decorator and { unique: true } in column options?

As written in the docs @Unique can only be applied to entire entities, not to a single column. For readability, I prefer for simple constraints @Column({ unique: true }) because it sits just on top of the affected variable name.

Another advantage of the @Unique syntax is the multi-column constraint ability. You can define multiple columns as one unique constraint: @Unique(["firstName", "secondName"]). This is not possible with the @Column decorator.

Finally, you can set a name for a particular constraint, when using @Unique decorator. The following single column constraint definition is functional equal, except @Unique sets a human readable name (Attention: @Unique expects the entity variable field name, not the actual database column name):

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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)