0
我在我的应用程序两个“模式”被分流到不同的文件:属于关联使用联想似乎并没有工作
ApplicationSession.model.js
module.exports = function(sequelize, DataTypes) {
const { INTEGER, DATE } = DataTypes;
var ApplicationSession = sequelize.define("applicationSession", {
sessionStart: DATE,
sessionEnd: DATE
}, {
associate: (models) => {
ApplicationSession.belongsTo(models.User, {
foreignKey: 'userId',
as: 'User',
});
}
});
return ApplicationSession;
};
User.model.js
module.exports = function(sequelize, DataTypes) {
const { STRING, INTEGER, DATE } = DataTypes;
var User = sequelize.define("user", {
name: STRING
}, {
associate: (models) => {
User.hasMany(models.ApplicationSession);
}
});
return User;
};
当保存表(DROPING/RECREATING)force: true
和手动丢弃仅用于理智时,永远不会为用户创建一个字段。
这里是我如何我的加载不同型号
import fs from 'fs';
import path from 'path';
import sequelize from '../connection';
var exports = {};
fs.readdirSync(__dirname).forEach(fileName => {
if(~fileName.indexOf('.model.js')) {
const subname = fileName.replace('.model.js', '');
const model = sequelize.import(path.join(__dirname, fileName));
exports[subname] = model;
}
});
export default exports;
当所有的车型在一个单一的文件中声明,我可以使用X.belongsTo(Y)
没有任何问题,所以我想我会尝试加入这我sequelize.import
下称
exports['ApplicationSession'].belongsTo(exports['User'], { as: 'User', foreignKey: 'userId' });
exports['User'].hasMany(exports['ApplicationSession']);
然而,这产生了不同的错误:
/node_modules/sequelize/lib/associations/mixin.js:96
throw new Error(this.name + '.' + Utils.lowercaseFirst(Type.toString()) + ' called with something that\'s not an instance of Sequelize.Model');
^
Error: applicationSession.function BelongsTo(source, target, options)
我该怎么做才能使人际关系发挥作用?
这是我的问题中的一个错误,他们是这样命名的,对不起。编辑:修复了问题 – Hobbyist
更新了我的anawer – drinchev