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时,它会自动创建 createdAt 和 updateAt 字段。每当创建或者更新时,就会更新值。

关闭自动创建 createdAt 和 updateAt

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 的世界里构建强大的数据模型。

相关推荐
子兮曰4 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰4 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
前端小万4 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝4 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
三十而立洋4 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
卡布鲁4 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
汉堡大王95274 天前
Jev:不是聊天机器人, 而是一个智能 if 语句
前端·人工智能·后端
梦想很大很大4 天前
从运行事实到回归证据:Workrun 的 Telemetry 与 Evaluation 实践
前端·人工智能·后端
计算机魔术师4 天前
Meta Muse agent 接入 Shopify 的 Shop Pay 实现代理式购物
前端
沙蒿同学4 天前
我用 Go 搭了一条 AI Agent 流水线:从 1 张商品图到一整套淘宝详情页
前端·javascript·后端