On this page
数据表设计和迁移
创建数据迁移表
shell
npx sequelize migration:generate --name=fava
1.执行完命令后,会在database / migrations / 目录下生成数据表迁移文件,然后定义
js
"use strict";
module.exports = {
up: async (queryInterface, Sequelize) => {
const { INTEGER, STRING, DATE, ENUM, TEXT } = Sequelize;
// 创建表
await queryInterface.createTable("fava", {
id: {
type: INTEGER(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
},
data: {
type: TEXT,
allowNull: false,
defaultValue: "",
comment: "内容",
},
type: {
type: ENUM,
values: ["emoticon", "text", "image", "video", "audio", "card"],
allowNull: false,
defaultValue: "text",
comment: "类型",
},
options: {
type: TEXT,
allowNull: false,
defaultValue: "",
comment: "其他参数",
},
user_id: {
type: INTEGER(20).UNSIGNED,
allowNull: false,
comment: "用户id",
// 定义外键(重要)
references: {
model: "user", // 对应表名称(数据表名称)
key: "id", // 对应表的主键
},
onUpdate: "restrict", // 更新时操作
onDelete: "cascade", // 删除时操作
},
created_at: DATE,
updated_at: DATE,
});
},
down: async (queryInterface) => {
await queryInterface.dropTable("fava");
},
};
创建模型
js
// app/model/fava.js
"use strict";
const crypto = require("crypto");
module.exports = (app) => {
const { INTEGER, STRING, DATE, ENUM, TEXT } = app.Sequelize;
// 配置(重要:一定要配置详细,一定要!!!)
const Fava = app.model.define("fava", {
id: {
type: INTEGER(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
},
data: {
type: TEXT,
allowNull: false,
defaultValue: "",
comment: "内容",
},
type: {
type: ENUM,
values: ["emoticon", "text", "image", "video", "audio", "card"],
allowNull: false,
defaultValue: "text",
comment: "类型",
},
options: {
type: TEXT,
allowNull: false,
defaultValue: "",
comment: "其他参数",
},
user_id: {
type: INTEGER(20).UNSIGNED,
allowNull: false,
comment: "用户id",
// 定义外键(重要)
references: {
model: "user", // 对应表名称(数据表名称)
key: "id", // 对应表的主键
},
onUpdate: "restrict", // 更新时操作
onDelete: "cascade", // 删除时操作
},
created_at: DATE,
updated_at: DATE,
});
return Fava;
};