灏天阁

Node/Koa2[45]: 创建微博

· Yin灏

数据模型

定义 Blog 模型

src/db/model/Blog.js

const seq = require("../seq");
const { INTEGER, STRING, TEXT } = require("../types");

const Blog = seq.define("blog", {
  userId: {
    type: INTEGER,
    allowNull: false,
    comment: "用户 ID",
  },
  content: {
    type: TEXT,
    allowNull: false,
    comment: "微博内容",
  },
  image: {
    type: STRING,
    comment: "图片地址",
  },
});

注册并创建外键

src/db/model/index.js

//...
const User = require("./User");
const Blog = require("./Blog");

// 创建外键
Blog.belongsTo(User, {
  foreignKey: "userId",
});

// User.hasMany(Blog)

module.exports = {
  User,
  Blog,
};

创建完模型要同步到数据库

# 同步命令
node src/db/sync.js

- Book Lists -