Egg-TS-Sequelize-TypeScript语法介绍

@Table

@Table({
  timestamps: true,
  ...
})

image-20220308112455509

let User = sequelize.define('user', {
}, {
    // 原生sequelize定义表方法的这里就是sequelize-typescript中的@Table
});

@Column

@Column({
    type: DataType.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false,
    unique: true,
    comment: '这是表的主键',
    ...
})
id: number;
let User = sequelize.define('user', {
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    }
}, {});

列类型快捷装饰器

  • @AllowNull(allowNull?: boolean):设置 attribute.allowNull(默认为 true)
  • @AutoIncrement:设置 attribute.autoIncrement=true
  • @Unique:设置 attribute.unique=true
  • @Default(value: any):设置 attribute.defaultValue 为指定值
  • @PrimaryKey:设置 attribute.primaryKey=true
  • @Comment(value: string):设置 attribute.comment 为指定的字符串
@Column({
    type: DataType.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false,
    unique: true,
    comment: '这是表的主键',
    ...
})
id: number;
  • 注意点: 结合使用时把 @Column 放到 最下面
@PrimaryKey
@AutoIncrement
@AllowNull(false)
@Unique
@Comment( '这是表的主键')
@Column({type: DataType.INTEGER});
id: number;

自动类型推断

可以从 JavaScript 类型自动推断出以下类型。其他必须明确定义。

JS 类型 推断类型
string STRING
boolean BOOLEAN
number INTEGER
Date DATE
Buffer BLOB

题外话

  • 大部分用法和 sequelize 都一样, 企业开发中只需对照文档阅读使用即可
  • 除此之外因为 sequelize 不是使用 ts 编写的, 所以在整合的时候需要做大量的配置和修改
  • 对于小白而言可能有些难度, 如果你想再简单一点, 那么你还可以在 TS 项目中使用 typeorm 来操作数据
  • typeormsequelize 都是数据库 ORM 框架, 但是 typeorm 是使用 TS 编写的, 所以在集成的时候相对简单
  • 但是由于 typeorm 比较新, 所以还有很多不足, 以及遇到问题的时候相关资料也并不是很多
  • 所以有空的时候建议可以尝试, 但如果个人能力还不够, 那么当前还不建议集成到企业级项目中进行生产使用

typeorm npm 官方地址:https://www.npmjs.com/package/typeorm

posted @   BNTang  阅读(560)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示