100 lines
2.6 KiB
JavaScript
100 lines
2.6 KiB
JavaScript
/**
|
||
* 政府后端模型索引文件
|
||
* @file index.js
|
||
* @description 导出所有模型并建立关联关系
|
||
*/
|
||
const { sequelize } = require('../config/database');
|
||
|
||
// 导入所有模型
|
||
const User = require('./User');
|
||
const AdminStaff = require('./AdminStaff');
|
||
const Department = require('./Department');
|
||
const Position = require('./Position');
|
||
const Farmer = require('./Farmer');
|
||
const HarmlessPlace = require('./HarmlessPlace');
|
||
const HarmlessRegistration = require('./HarmlessRegistration');
|
||
const Material = require('./Material');
|
||
const Slaughterhouse = require('./Slaughterhouse');
|
||
const EpidemicAgency = require('./EpidemicAgency');
|
||
const SmartCollar = require('./SmartCollar');
|
||
const SmartEarmark = require('./SmartEarmark');
|
||
const SmartHost = require('./SmartHost');
|
||
const WarehouseTransaction = require('./WarehouseTransaction');
|
||
|
||
// 初始化所有模型
|
||
const initModels = () => {
|
||
try {
|
||
// 处理直接导出的模型
|
||
if (User && typeof User !== 'function') {
|
||
// User模型已经直接导出,不需要额外处理
|
||
}
|
||
|
||
// 处理需要sequelize参数的模型
|
||
const modelsToInit = [
|
||
AdminStaff,
|
||
Department,
|
||
Position,
|
||
Farmer,
|
||
HarmlessPlace,
|
||
HarmlessRegistration,
|
||
Material,
|
||
Slaughterhouse,
|
||
EpidemicAgency,
|
||
SmartCollar,
|
||
SmartEarmark,
|
||
SmartHost,
|
||
WarehouseTransaction
|
||
];
|
||
|
||
// 初始化模型
|
||
modelsToInit.forEach(modelFactory => {
|
||
if (typeof modelFactory === 'function') {
|
||
// 调用函数获取模型实例
|
||
const model = modelFactory(sequelize);
|
||
// 将初始化后的模型赋值回原来的变量
|
||
Object.assign(module.exports, { [model.name]: model });
|
||
}
|
||
});
|
||
|
||
console.log('✅ 所有政府后端模型初始化完成');
|
||
} catch (error) {
|
||
console.error('❌ 政府后端模型初始化失败:', error);
|
||
}
|
||
};
|
||
|
||
// 初始化模型
|
||
initModels();
|
||
|
||
// 导出sequelize和所有模型
|
||
module.exports = {
|
||
sequelize,
|
||
User,
|
||
AdminStaff,
|
||
Department,
|
||
Position,
|
||
Farmer,
|
||
HarmlessPlace,
|
||
HarmlessRegistration,
|
||
Material,
|
||
Slaughterhouse,
|
||
EpidemicAgency,
|
||
SmartCollar,
|
||
SmartEarmark,
|
||
SmartHost,
|
||
WarehouseTransaction
|
||
};
|
||
|
||
// 同步所有模型到数据库(可选)
|
||
const syncModels = async (options = {}) => {
|
||
try {
|
||
await sequelize.sync(options);
|
||
console.log('✅ 政府后端所有模型已同步到数据库');
|
||
return true;
|
||
} catch (error) {
|
||
console.error('❌ 政府后端模型同步失败:', error);
|
||
return false;
|
||
}
|
||
};
|
||
|
||
// 添加syncModels到导出
|
||
module.exports.syncModels = syncModels; |