📜  typeorm @unique - TypeScript (1)

📅  最后修改于: 2023-12-03 15:05:39.126000             🧑  作者: Mango

TypeORM @Unique

TypeORM is an Object-Relational Mapping (ORM) library for TypeScript and JavaScript. It provides a way for developers to work with databases using an object-oriented approach. One of the features of TypeORM is the @Unique decorator.

What is @Unique?

The @Unique decorator is used to apply a unique constraint to a column in a database table. This means that the column can only contain unique values, and any attempt to insert a duplicate value will result in an error.

For example:

import { Entity, Column, PrimaryGeneratedColumn, Unique } from 'typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  @Unique(['email'])
  email: string;

  @Column()
  password: string;
}

In the above code, the email column is marked as @Unique. This means that any attempt to insert a duplicate email value will result in an error.

How to use @Unique?

To use the @Unique decorator, you need to import it from the TypeORM library and apply it to the appropriate column in your entity class.

  1. First, you need to install the TypeORM library using npm:

    npm install typeorm
    
  2. Then, you need to create an entity class that represents your database table. Here's an example:

    import { Entity, Column, PrimaryGeneratedColumn, Unique } from 'typeorm';
    
    @Entity()
    export class User {
      @PrimaryGeneratedColumn()
      id: number;
    
      @Column()
      name: string;
    
      @Column()
      @Unique(['email'])
      email: string;
    
      @Column()
      password: string;
    }
    

    In this example, we're creating an entity class called User that represents a database table. We're using the @Unique decorator to apply a unique constraint to the email column.

  3. Finally, you can use the TypeORM library to interact with the database using your entity class. Here's an example:

    import { createConnection } from 'typeorm';
    import { User } from './user.entity';
    
    async function createUser() {
      const connection = await createConnection();
    
      const user = new User();
      user.name = 'John Doe';
      user.email = 'john.doe@example.com';
      user.password = 'password123';
    
      await connection.manager.save(user);
    }
    

    In this example, we're using the createConnection function from the TypeORM library to connect to the database. Then, we're creating a new User object and setting its properties. Finally, we're using the save method of the connection.manager object to save the user object to the database.

Conclusion

The @Unique decorator is a powerful feature of the TypeORM library that allows you to apply unique constraints to columns in your database tables. This can help to ensure data integrity and prevent duplicate values from being inserted into your database.