nullable 字段用了? 而不是!, 类型没加 null 错误示例:
@Column({
name: 'description',
type: 'text',
nullable: true,
comment: '容器配置描述'
})
description?: string;
正确示例:
@Column({
name: 'description',
type: 'text',
nullable: true,
comment: '容器配置描述'
})
description!: string | null;
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
import { z } from '@hono/zod-openapi'
@Entity('table_name') // 使用小写下划线命名表名
export class EntityName {
// 字段定义...
}
@PrimaryGeneratedColumn({ unsigned: true }) // 必须使用无符号整数
id!: number; // 使用非空断言(!)和明确类型
@Column({
name: '字段名称', // 必须添加并与数据表字段名称一致
type: 'varchar', // 明确指定数据库类型
length: 255, // 字符串必须指定长度
nullable: true, // 明确是否可为空
default: undefined, // 默认值(可选)
comment: '字段说明' // 必须添加中文注释
})
fieldName!: FieldType; // 类型必须明确
| 业务类型 | 数据库类型 | TypeScript 类型 |
|---|---|---|
| 主键ID | int unsigned | number |
| 短文本 | varchar(length) | string |
| 长文本 | text | string |
| 整数 | int | number |
| 小数 | decimal(precision,scale) | number |
| 布尔状态 | tinyint | number (0/1) |
| 日期时间 | timestamp | Date |
// 禁用状态 (0启用 1禁用)
@Column({ name: 'is_disabled', type: 'tinyint', default: 1 })
isDisabled!: number;
// 删除状态 (0未删除 1已删除)
@Column({ name: 'is_deleted',type: 'tinyint', default: 0 })
isDeleted!: number;
// 创建时间 (自动设置)
@Column({
name: 'created_at',
type: 'timestamp',
default: () => 'CURRENT_TIMESTAMP'
})
createdAt!: Date;
// 更新时间 (自动更新)
@Column({
name: 'updated_at',
type: 'timestamp',
default: () => 'CURRENT_TIMESTAMP',
onUpdate: 'CURRENT_TIMESTAMP'
})
updatedAt!: Date;
export const EntitySchema = z.object({
id: z.number().int().positive().openapi({ description: 'ID说明' }),
// 字符串字段
fieldName: z.string()
.max(255)
.nullable()
.openapi({
description: '字段说明',
example: '示例值'
}),
// 数字字段
numberField: z.number()
.default(默认值)
.openapi({...}),
// 日期字段
dateField: z.date().openapi({...})
});