乐闻世界logo
搜索文章和话题

How to create autoincrement integer field in TypeORM migration?

1个答案

1

Creating an auto-incrementing integer field in TypeORM typically involves several key steps, especially when using database migration tools. Here are the steps to create an auto-incrementing integer field in TypeORM migrations:

Step 1: Define the Entity

First, you need to define an auto-incrementing field in your TypeORM entity class. Suppose you have an entity named User and you want to add an auto-incrementing id field as the primary key.

typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"; @Entity() export class User { @PrimaryGeneratedColumn() id: number; @Column() name: string; }

Here, the @PrimaryGeneratedColumn() decorator informs TypeORM that this field is an auto-incrementing primary key.

Step 2: Create the Migration

Next, you need to create a migration to apply these changes to the database. You can use TypeORM's CLI tool to automatically generate the migration, which can be done with the following command:

bash
typeorm migration:generate -n CreateUserTable

This command creates a new migration file in your project's designated migration directory, with a filename typically including a timestamp and the migration name you provided.

Step 3: Edit the Migration File

The generated migration file will contain SQL statements based on your current entity state. For the auto-incrementing id field, the migration file should resemble the following code:

typescript
import {MigrationInterface, QueryRunner} from "typeorm"; export class CreateUserTable1607529924106 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<void> { await queryRunner.query(` CREATE TABLE "user" ( "id" SERIAL NOT NULL, "name" character varying NOT NULL, CONSTRAINT "PK_a3ffb1c0c8416b9fc6f907b7433" PRIMARY KEY ("id") ) `); } public async down(queryRunner: QueryRunner): Promise<void> { await queryRunner.query(`DROP TABLE "user"`); } }

Note that the id field uses the SERIAL keyword, which in PostgreSQL represents an auto-incrementing integer. Different databases may use different keywords (e.g., AUTO_INCREMENT in MySQL).

Step 4: Run the Migration

Finally, you need to run the migration to update the database schema. This can be done with the following command:

bash
typeorm migration:run

After running this command, a new user table will be created in the database, with the id field configured as auto-incrementing.

Summary

By following these steps, you can successfully create and migrate an auto-incrementing integer field in TypeORM. These steps ensure that database schema changes can be tracked and managed through version control.

2024年6月29日 12:07 回复

你的答案