SQL 转 TypeORM:从 DDL 脚本生成模型
下面不是示意图:这是生成器对左边脚本的真实输出。在编辑器里点「Codegen → TypeORM」得到的就是同一份代码。
输入schema.sql
CREATE TABLE users (
id BIGINT NOT NULL PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
full_name VARCHAR(120),
is_active BOOLEAN NOT NULL,
created_at TIMESTAMP NOT NULL
);
CREATE TABLE orders (
id BIGINT NOT NULL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id),
total DECIMAL(12,2) NOT NULL,
note TEXT,
placed_at TIMESTAMP NOT NULL
);输出entities.ts
import { Column, Entity, JoinColumn, ManyToOne, PrimaryColumn } from "typeorm";
@Entity("users")
export class Users {
@PrimaryColumn({ type: "bigint" })
id!: string;
@Column({ type: "varchar", length: 255, unique: true })
email!: string;
@Column({ type: "varchar", length: 120, nullable: true, name: "full_name" })
fullName!: string | null;
@Column({ type: "boolean", name: "is_active" })
isActive!: boolean;
@Column({ type: "timestamp", name: "created_at" })
createdAt!: Date;
}
@Entity("orders")
export class Orders {
@PrimaryColumn({ type: "bigint" })
id!: string;
@Column({ type: "bigint", name: "user_id" })
userId!: string;
@Column({ type: "decimal", precision: 12, scale: 2 })
total!: number;
@Column({ type: "text", nullable: true })
note!: string | null;
@Column({ type: "timestamp", name: "placed_at" })
placedAt!: Date;
@ManyToOne(() => Users)
@JoinColumn({ name: "user_id" })
users!: Users;
}打开编辑器
脚本留在浏览器里:解析和生成都在您的机器上进行,不会上传到服务器。
类型如何对应
| 在 SQL 里 | 在模型里 |
|---|---|
BIGINT | string |
VARCHAR(255) | string |
BOOLEAN | boolean |
TIMESTAMP | Date |
DECIMAL(12,2) | number |
TEXT | string | null |
- 可空字段
nullable: true- 列名
name: "full_name"- 关系
@ManyToOne(() => Users)