我有两个模型category
和sub_category
,我已经实现了one-to-many
关联B但我得到了类似sub category Error: sub_category.belongsTo called with something that's not a subclass of Sequelize.Model
的错误。为什么?
范畴模型
const { DataTypes } = require("sequelize");
const { getConnection } = require("../helper/databaseConnection");
const subcat = require("./subCategory");
const categoryModel = {
category_id: {
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
},
category_name: {
type: DataTypes.STRING,
allowNull: false,
},
};
let category = null;
const initCategoryModel = async () => {
try {
if (category) return category;
const sequelize = await getConnection();
category = sequelize.define("category", categoryModel, {
freezeTableName: true,
});
category.hasMany(subcat, {
foreignKey: "category_id",
onDelete: "CASCADE",
});
await category.sync({ alter: true });
return category;
} catch (err) {
console.log("category", err);
}
};
module.exports = { initCategoryModel };
子类模型
const { DataTypes } = require("sequelize");
const { getConnection } = require("../helper/databaseConnection");
const category = require("./category");
const subcatModel = {
subcat_id: {
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
},
subcat_name: {
type: DataTypes.STRING,
allowNull: false,
},
};
let subcat = null;
const initSubcatModel = async () => {
try {
if (subcat) return subcat;
const sequelize = await getConnection();
subcat = sequelize.define("sub_category", subcatModel, {
freezeTableName: true,
});
subcat.belongsTo(category, {
foreignKey: "category_id",
onDelete: "CASCADE",
});
await subcat.sync({ alter: true });
return subcat;
} catch (err) {
console.log("sub category", err);
}
};
module.exports = { initSubcatModel };
这里类别具有许多子类别,
1条答案
按热度按时间holgip5t1#
从你粘贴的代码来看,你似乎没有导出subcat或category,而是导出了init函数。
由于存在循环依赖,无论如何都会有一个问题,取决于init函数被调用的顺序,你会让subcat或category被undefined(因为相应的init函数还没有被调用)。
您应该将模型定义、模型关联和模型同步分成三个独立的步骤,确保首先调用模型定义,然后进行关联,最后进行同步。