On this page
数据表设计和迁移
创建数据迁移表
shell
npx sequelize migration:generate --name=fava
1.执行完命令后,会在database / migrations / 目录下生成数据表迁移文件,然后定义
js
"use strict";
module.exports = {
up: (queryInterface, Sequelize) => {
const { INTEGER, STRING, DATE, ENUM, TEXT } = Sequelize;
return queryInterface.createTable("fava", {
id: {
type: INTEGER(20),
primaryKey: true,
autoIncrement: true,
},
user_id: {
type: INTEGER,
allowNull: false,
defaultValue: 0,
comment: "用户id",
references: {
model: "user",
key: "id",
},
onDelete: "cascade",
onUpdate: "restrict", // 更新时操作
},
video_id: {
type: INTEGER,
allowNull: false,
defaultValue: 0,
comment: "视频id",
references: {
model: "video",
key: "id",
},
onDelete: "cascade",
onUpdate: "restrict", // 更新时操作
},
created_time: DATE,
updated_time: DATE,
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable("fava");
},
};
- 执行 migrate 进行数据库变更
shell
npx sequelize db:migrate
模型创建
js
// app/model/fava.js
module.exports = (app) => {
const { STRING, INTEGER, DATE, ENUM, TEXT } = app.Sequelize;
const Fava = app.model.define("fava", {
id: {
type: INTEGER(20),
primaryKey: true,
autoIncrement: true,
},
user_id: {
type: INTEGER,
allowNull: false,
defaultValue: 0,
comment: "用户id",
},
video_id: {
type: INTEGER,
allowNull: false,
defaultValue: 0,
comment: "视频id",
},
created_time: DATE,
updated_time: DATE,
});
// 关联关系
Fava.associate = function (models) {
// 关联作者
Fava.belongsTo(app.model.User);
// 关联视频
Fava.belongsTo(app.model.Video);
};
return Fava;
};