On this page
数据表设计和迁移
创建数据迁移表
shell
npx sequelize migration:generate --name=user
1.执行完命令后,会在database / migrations / 目录下生成数据表迁移文件,然后定义
js
"use strict";
module.exports = {
up: (queryInterface, Sequelize) => {
const { INTEGER, STRING, DATE, ENUM, TEXT } = Sequelize;
return queryInterface.createTable("user", {
id: {
type: INTEGER(20),
primaryKey: true,
autoIncrement: true,
},
username: {
type: STRING(30),
allowNull: false,
defaultValue: "",
comment: "用户名",
unique: true,
},
nickname: {
type: STRING(30),
allowNull: false,
defaultValue: "",
comment: "...",
},
email: {
type: STRING(160),
allowNull: false,
defaultValue: "",
comment: "邮箱",
},
password: {
type: STRING,
allowNull: false,
defaultValue: "",
comment: "密码",
},
avatar: {
type: STRING,
allowNull: true,
defaultValue: "",
comment: "头像",
},
phone: {
type: STRING(11),
allowNull: false,
defaultValue: "",
comment: "手机",
},
sex: {
type: ENUM,
values: ["男", "女", "保密"],
allowNull: false,
defaultValue: "男",
comment: "性别",
},
desc: {
type: TEXT,
allowNull: false,
defaultValue: "",
comment: "个性签名",
},
total_size: {
type: INTEGER,
defaultValue: 0,
comment: "网盘总大小,单位:kb",
},
used_size: {
type: INTEGER,
defaultValue: 0,
comment: "网盘已使用大小,单位:kb",
},
created_time: DATE,
updated_time: DATE,
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable("user");
},
};
- 执行 migrate 进行数据库变更
shell
npx sequelize db:migrate
模型创建
js
// app/model/user.js
const crypto = require("crypto");
module.exports = (app) => {
const { STRING, INTEGER, DATE, ENUM, TEXT } = app.Sequelize;
const User = app.model.define("user", {
id: {
type: INTEGER(20),
primaryKey: true,
autoIncrement: true,
},
username: {
type: STRING(30),
allowNull: false,
defaultValue: "",
comment: "用户名",
unique: true,
},
nickname: {
type: STRING(30),
allowNull: false,
defaultValue: "",
comment: "...",
},
email: {
type: STRING(160),
allowNull: false,
defaultValue: "",
comment: "邮箱",
},
password: {
type: STRING,
allowNull: false,
defaultValue: "",
comment: "密码",
set(val) {
const hmac = crypto.createHash("sha256", app.config.crypto.secret);
hmac.update(val);
let hash = hmac.digest("hex");
this.setDataValue("password", hash);
},
},
avatar: {
type: STRING,
allowNull: true,
defaultValue: "",
comment: "头像",
},
phone: {
type: STRING(11),
allowNull: false,
defaultValue: "",
comment: "手机",
},
sex: {
type: ENUM,
values: ["男", "女", "保密"],
allowNull: false,
defaultValue: "男",
comment: "性别",
},
desc: {
type: TEXT,
allowNull: false,
defaultValue: "",
comment: "个性签名",
},
total_size: {
type: INTEGER,
defaultValue: 10485760,
comment: "网盘总大小,单位:kb",
},
used_size: {
type: INTEGER,
defaultValue: 0,
comment: "网盘已使用大小,单位:kb",
},
created_time: DATE,
updated_time: DATE,
});
// User.associate = function (models) {
// // 关联文件
// User.hasMany(app.model.File);
// }
return User;
};