我试图将两张桌子联系起来。
这两个表是员工表和部门表。
但由于某种原因,没有建立关系。
这是我的代码和错误。我做错了什么?
我想在员工表中有多个部门表。
如果我不在findAll中包含它,它可以正常工作。但是,包括它们会导致问题。
//
module.exports = function (sequelize, DataTypes) {
const department = sequelize.define('DEPT', {
deptNo: {
field: 'DEPTNO',
type: DataTypes.INTEGER ,
primaryKey: true ,
autoIncrement: true
},
deptName: {
field: 'DEPTNAME',
type: DataTypes.STRING(32)
},
floor: {
field: 'FLOOR',
type: DataTypes.INTEGER
},
}, {
// don't use camelcase for automatically added attributes but underscore style
// so updatedAt will be updated_at
underscored: true,
// disable the modification of tablenames; By default, sequelize will automatically
// transform all passed model names (first parameter of define) into plural.
// if you don't want that, set the following
freezeTableName: true,
// define the table's name
tableName: 'DEPARTMENT'
});
department.associate = function (models){
department.belongsTo(models.EMP , {
foreignkey : "empId"
});
};
return department;
}
module.exports = function (sequelize, DataTypes) {
const employee = sequelize.define('EMP', {
empNo: {
field: 'EMPNO',
type: DataTypes.INTEGER ,
primaryKey: true ,
autoIncrement: true
},
empName: {
field: 'EMPNAME',
type: DataTypes.STRING(32)
},
title: {
field: 'TITLE',
type: DataTypes.STRING(32)
},
dNo: {
field: 'DNO',
type: DataTypes.INTEGER
},
salary: {
field: 'SALARY',
type: DataTypes.INTEGER
}
}, {
// don't use camelcase for automatically added attributes but underscore style
// so updatedAt will be updated_at
underscored: true,
// disable the modification of tablenames; By default, sequelize will automatically
// transform all passed model names (first parameter of define) into plural.
// if you don't want that, set the following
freezeTableName: true,
// define the table's name
tableName: 'EMPLOYEE'
});
employee.associations = function (models) {
employee.hasMany(models.DEPT , {
foreignkey : "empId"
});
};
return employee;
}
router.get('/', function(req, res, next) {
models.EMP.findAll({
include : [{model :models.DEPT}]
})
.then(results => {
res.json(results);
})
.catch( err => {
console.error(err);
});
});
错误:SequelizeEagerLoadingError:DEPT与EMP无关!
答案 0 :(得分:0)
你应该像这样:
const models = {};
glob.sync(path.join(__dirname, 'path to models e.g. **/*.js'))
.forEach(file => {
const model = sequelize.import(file);
models[model.name] = model;
});
Object.keys(models).forEach(model => {
if (models[model].associate) {
models[model].associate(models);
}
});
export {models};