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

相关推荐
万叶学编程1 小时前
Day02-JavaScript-Vue
前端·javascript·vue.js
前端李易安3 小时前
Web常见的攻击方式及防御方法
前端
PythonFun3 小时前
Python技巧:如何避免数据输入类型错误
前端·python
知否技术3 小时前
为什么nodejs成为后端开发者的新宠?
前端·后端·node.js
hakesashou3 小时前
python交互式命令时如何清除
java·前端·python
天涯学馆3 小时前
Next.js与NextAuth:身份验证实践
前端·javascript·next.js
HEX9CF4 小时前
【CTF Web】Pikachu xss之href输出 Writeup(GET请求+反射型XSS+javascript:伪协议绕过)
开发语言·前端·javascript·安全·网络安全·ecmascript·xss
ConardLi4 小时前
Chrome:新的滚动捕捉事件助你实现更丝滑的动画效果!
前端·javascript·浏览器
ConardLi4 小时前
安全赋值运算符,新的 JavaScript 提案让你告别 trycatch !
前端·javascript