egg中使用sequelize 設定一對多資料表
阿新 • • 發佈:2022-04-12
拿一個數據字典舉例
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; };
♥ 如果本章內容為您提供了幫助 請點選推薦哦