Nest.js 中 Sequelize Model 入门指南:构建强大数据模型

什么是Model

它是数据库的表的抽象。在 Sequelize 中,它是一个扩展模型的类。

Model 定义

在 Sequelize 中有两种方式来定义 Model,

在内部,sequelize.define 调用 Model.init,因此这两种方法本质上是等效的。

sequelize.define定义Model

php 复制代码
const { DataTypes } = require("sequelize");
​
​
const Book = sequelize.define("book", {
    author: DataTypes.TEXT,
    bookName: DataTypes.TEXT,
    price:DataTypes.INTEGER,
    bid:DataTypes.INTEGER,
  },{
    tableName:'book'
  });
​
​
​
export default Book; 

扩展Model

scala 复制代码
import sequelize from "../sequelize";
const { Sequelize, Model, DataTypes } = require("sequelize");
​
export default class Goods extends Model {}
​
​
Goods.init({
    goodsName:{
        type: DataTypes.STRING,
    },
    goodsType:{
        type: DataTypes.STRING,
    },
    place:{
        type: DataTypes.STRING,
    },
},{
​
    sequelize, // We need to pass the connection instance
    modelName: 'Goods' // We need to choose the model name
  })

Model name

默认情况下,如果未给出表名,Sequelize 会自动复数模型名称并将其用作表名。

强制表名等于Model Name

freezeTableName: true 关闭Model name 为负数

arduino 复制代码
sequelize.define('User', {
  // ... (attributes)
}, {
  freezeTableName: true  
});

也可以全局进行配置,当再次定义 Model 时,无须配置 freezeTableName。

arduino 复制代码
const sequelize = new Sequelize('sqlite::memory:', {
  define: {
    freezeTableName: true
  }
});

直接提供表名

php 复制代码
sequelize.define('User', {
​
}, {
  tableName: 'Employees'
});

Model 同步数据库

将定义的Model 和 数据库关联,Model 变化,数据库也跟着变化。我们可以通过调用 model.sync(option) 异步函数 来和数据库同步。

  • Model.sync()- 如果表不存在,这将创建表(如果它已经存在,则不执行任何操作)
  • Model.sync({ force: true }) - 这将创建表,如果它已经存在,则首先删除它
  • Model.sync({ alter: true }) - 这将检查数据库中表的当前状态(它有哪些列,它们的数据类型是什么等),然后在表中执行必要的更改以使其与模型匹配。
scala 复制代码
import sequelize from "../sequelize";
const { Sequelize, Model, DataTypes } = require("sequelize");
​
export default class Goods extends Model {}
​
​
Goods.init({
    goodsName:{
        type: DataTypes.STRING,
    },
    goodsType:{
        type: DataTypes.STRING,
    },
    place:{
        type: DataTypes.STRING,
    },
},{
    // Other model options go here
    sequelize, // We need to pass the connection instance
    modelName: 'Goods' // We need to choose the model name
  })
​
​
​
Goods.sync({ force: true })  //同步到数据库

自动同步所有Model

可以使用 sequelize.sync() 同步所有Model。

javascript 复制代码
await sequelize.sync({ force: true });
console.log("All models were synchronized successfully.");

删除数据库表

通过 .drop() 删除与Model 相关的数据库表 . (尽量少用)

csharp 复制代码
await Goods.drop();

时间戳

默认情况,当你创建一个Model时,它会自动创建 createdAtupdateAt 字段。每当创建或者更新时,就会更新值。

关闭自动创建 createdAtupdateAt

arduino 复制代码
sequelize.define('User', {
  // ... (attributes)
}, {
  timestamps: false
});

只开启 其中 1 个字段并自定义 字段名

scala 复制代码
class Foo extends Model {}
Foo.init({ /* attributes */ }, {
  sequelize,
​
​
  timestamps: true,
​
 //关闭创建时间,   默认是都开启的
  createdAt: false,
​
  //更新字段自定义
  updatedAt: 'updateTime'
});

字段默认值

默认情况下,Sequelize 假定列的默认值为 NULL可以通过将特定的defaultValue传递给列定义来更改此行为:

scala 复制代码
​
import sequelize  from "config/sequelize";
const { Sequelize, Model, DataTypes } = require("sequelize");
​
export default class Goods extends Model {}
​
​
Goods.init({
    goodsName:{
        type: DataTypes.STRING,
    },
    goodsType:{
        type: DataTypes.STRING,
    },
    place:{
        type: DataTypes.STRING,
        defaultValue: "中国"
    },
},{
​
    sequelize, // We need to pass the connection instance
    modelName: 'Goods', // We need to choose the model name
    timestamps: false
  })

一些特殊值,如DataTypes.NOW也被接受:

sql 复制代码
sequelize.define('Foo', {
  bar: {
    type: DataTypes.DATETIME,
    defaultValue: DataTypes.NOW
    // This way, the current date/time will be used to populate this column (at the moment of insertion)
  }
});

列的数据类型

在模型中定义的每个列都必须具有数据类型。续集提供了许多内置数据类型。若要访问内置数据类型,必须导入DataTypes:

字符串

scss 复制代码
DataTypes.STRING             // VARCHAR(255)
DataTypes.STRING(1234)       // VARCHAR(1234)
DataTypes.STRING.BINARY      // VARCHAR BINARY
DataTypes.TEXT               // TEXT
DataTypes.TEXT('tiny')       // TINYTEXT
DataTypes.CITEXT             // CITEXT          PostgreSQL and SQLite only.
DataTypes.TSVECTOR           // TSVECTOR        PostgreSQL only.

布尔

arduino 复制代码
DataTypes.BOOLEAN            // TINYINT(1)

数字

scss 复制代码
DataTypes.INTEGER            // INTEGER
DataTypes.BIGINT             // BIGINT
DataTypes.BIGINT(11)         // BIGINT(11)
​
DataTypes.FLOAT              // FLOAT
DataTypes.FLOAT(11)          // FLOAT(11)
DataTypes.FLOAT(11, 10)      // FLOAT(11,10)
​
DataTypes.REAL               // REAL            PostgreSQL only.
DataTypes.REAL(11)           // REAL(11)        PostgreSQL only.
DataTypes.REAL(11, 12)       // REAL(11,12)     PostgreSQL only.
​
DataTypes.DOUBLE             // DOUBLE
DataTypes.DOUBLE(11)         // DOUBLE(11)
DataTypes.DOUBLE(11, 10)     // DOUBLE(11,10)
​
DataTypes.DECIMAL            // DECIMAL
DataTypes.DECIMAL(10, 2)     // DECIMAL(10,2)
​
​

日期

sql 复制代码
DataTypes.DATE       // DATETIME for mysql / sqlite, TIMESTAMP WITH TIME ZONE for postgres
DataTypes.DATE(6)    // DATETIME(6) for mysql 5.6.4+. Fractional seconds support with up to 6 digits of precision
DataTypes.DATEONLY   // DATE without time

最后

关注 Nest 专栏,这里汇聚了关于 Nest.js 的丰富知识与实践。今天,我们将一同探索 [Nest.js 中 Sequelize Model 入门指南]。让我们深入学习,在 Nest.js 的世界里构建强大的数据模型。

相关推荐
啃火龙果的兔子3 分钟前
前端单元测试覆盖率工具有哪些,分别有什么优缺点
前端·单元测试
「、皓子~30 分钟前
后台管理系统的诞生 - 利用AI 1天完成整个后台管理系统的微服务后端+前端
前端·人工智能·微服务·小程序·go·ai编程·ai写作
就改了33 分钟前
Ajax——在OA系统提升性能的局部刷新
前端·javascript·ajax
凌冰_35 分钟前
Ajax 入门
前端·javascript·ajax
京东零售技术1 小时前
京东小程序JS API仓颉改造实践
前端
老A技术联盟1 小时前
从小白入门,基于Cursor开发一个前端小程序之Cursor 编程实践与案例分析
前端·小程序
风铃喵游1 小时前
构建引擎: 打造小程序编译器
前端·小程序·架构
sunbyte1 小时前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | ThemeClock(主题时钟)
前端·javascript·css·vue.js·前端框架·tailwindcss
小飞悟1 小时前
🎯 什么是模块化?CommonJS 和 ES6 Modules 到底有什么区别?小白也能看懂
前端·javascript·设计
浏览器API调用工程师_Taylor1 小时前
AOP魔法:一招实现登录弹窗的全局拦截与动态处理
前端·javascript·vue.js