Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typeorm

In TypeORM you have the possibility to set a unique flag in the column options, or to set column(s) to unique for the entity.

When would you use which, and what's the difference there?

@Unique(["firstName"])

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

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

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

like image 560
Karl Adler Avatar asked Sep 08 '20 11:09

Karl Adler


People also ask

How do you make a column unique in TypeORM?

To create a unique constraint with TypeORM, we can use the unique parameter. If we want to use multiple columns for our unique constraint, we need to use the @Unique decorator. An important thing about the @Unique decorator is that we supply it with the field names, not the names of the columns.

What is PrimaryGeneratedColumn?

@PrimaryGeneratedColumn() field is used to specify the primary column as well as to auto generate the column value in the database.


1 Answers

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;
...
like image 131
Rod Rob Avatar answered Oct 06 '22 05:10

Rod Rob