灏天阁

Node/Koa2[10]: sequelize创建关联

· Yin灏

创建 Blog 模型

src/model.js

const Sequelize = require("sequelize");
const seq = require("./seq");
// 创建 User 模型
const User = seq.define("user", {
  // id 会自动创建,并设为主键、自增
  userName: {
    type: Sequelize.STRING, // 对应 varchar(255)
    allowNull: false,
  },
  password: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  nickName: {
    type: Sequelize.STRING,
    comment: "昵称",
  },
});

// 创建 Blog 模型
const Blog = seq.define("blog", {
  title: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  content: {
    type: Sequelize.TEXT,
    allowNull: false,
  },
  userId: {
    type: Sequelize.INTEGER,
    allowNull: false,
  },
});

// 外键关联
// belongsTo 属于
// 多对一的关系
Blog.belongsTo(User, {
  // 创建外键 Blog.userId -> User.id
  foreignKey: "userId",
});
// 一对多的关系
User.hasMany(Blog, {
  // 创建外键 Blog.userId -> User.id
  foreignKey: "userId",
});

module.exports = {
  User,
  Blog,
};

生成 ER 图

- Book Lists -