egg中使用sequelize 设置一对多数据表

拿一个数据字典举例
A表

"use strict";
module.exports = (app) => {
  const { DataTypes } = app.Sequelize;

  const Dict = app.model.define("dict", {
    id: {
      type: DataTypes.UUID,
      defaultValue: app.Sequelize.UUIDV4,
      primaryKey: true,
      notNull: true,
      comment: "ID",
    },
    code: {
      type: DataTypes.STRING(255),
      notNull: true,
      comment: "字典编号",
    },
    name: {
      type: DataTypes.TEXT,
      notNull: true,
      comment: "字典名称",
    }
  });
  // 建立联系
  Dict.associate = function () {
        app.model.Dict.hasMany(app.model.DictItem, { foreignKey: "dict_id" });
  };
  Dict.sync();
  return Dict;
};

B表

"use strict";
module.exports = (app) => {
  const { DataTypes } = app.Sequelize;

  const DictItem = app.model.define("dict_item", {
    id: {
      type: DataTypes.UUID,
      defaultValue: app.Sequelize.UUIDV4,
      primaryKey: true,
      notNull: true,
    },
    dict_id: {
      type: DataTypes.UUID,
      comment: "主表ID",
    },
    label: {
      type: DataTypes.STRING(255),
      notNull: true,
      comment: "字典key",
    },
    value: {
      type: DataTypes.STRING(255),
      notNull: true,
      comment: "字典value",
    },
  });

  DictItem.sync();
  return DictItem;
};

♥ 如果本章内容为您提供了帮助 请点击推荐哦

posted @ 2022-04-12 09:29  我不是张三  阅读(146)  评论(0编辑  收藏  举报