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