Skip to content
关注公众号,获取新课通知

数据表设计和迁移


创建数据迁移表

shell
npx sequelize migration:generate --name=follow

1.执行完命令后,会在database / migrations / 目录下生成数据表迁移文件,然后定义

js
"use strict";

module.exports = {
  up: (queryInterface, Sequelize) => {
    const { INTEGER, STRING, DATE, ENUM, TEXT } = Sequelize;
    return queryInterface.createTable("follow", {
      id: {
        type: INTEGER(20),
        primaryKey: true,
        autoIncrement: true,
      },
      user_id: {
        type: INTEGER,
        allowNull: true,
        comment: "用户id",
        references: {
          model: "user",
          key: "id",
        },
        onDelete: "cascade",
        onUpdate: "restrict", // 更新时操作
      },
      follow_id: {
        type: INTEGER,
        allowNull: true,
        comment: "关注id",
        references: {
          model: "user",
          key: "id",
        },
        onDelete: "cascade",
        onUpdate: "restrict", // 更新时操作
      },
      created_time: DATE,
      updated_time: DATE,
    });
  },

  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable("follow");
  },
};
  • 执行 migrate 进行数据库变更
shell
npx sequelize db:migrate

模型创建

js
// app/model/follow.js
module.exports = (app) => {
  const { STRING, INTEGER, DATE, ENUM, TEXT } = app.Sequelize;

  const Follow = app.model.define("follow", {
    id: {
      type: INTEGER(20),
      primaryKey: true,
      autoIncrement: true,
    },
    user_id: {
      type: INTEGER,
      allowNull: true,
      comment: "用户id",
    },
    follow_id: {
      type: INTEGER,
      allowNull: true,
      defaultValue: 0,
      comment: "关注id",
    },
    created_time: DATE,
    updated_time: DATE,
  });

  // 关联关系
  Follow.associate = function (models) {
    // 关联粉丝
    Follow.belongsTo(app.model.User, {
      as: "user_follow",
      foreignKey: "follow_id",
    });
    // 关联粉丝
    Follow.belongsTo(app.model.User, {
      as: "user_fen",
      foreignKey: "user_id",
    });
  };

  return Follow;
};