I'm working on a NodeJS application and I'm trying to setup associations in Sequelize.
I put a console.log() in /models/index.js to verify whether each model's associate is being called but the line is never being hit and my database tables do not have the foreign key references that I've defined in my associate method.
I've spent days trying to solve this issue to no avail.
It's finding all the models just fine (I checked the db[] array), it just appears that, for whatever reason, myModel.associate is undefined.
Any help would be GREATLY appreciated.
/models/index.js
'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../../config/config.json')[env];
var db = {};
if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
var sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(function(file) {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if (db[modelName].associate) { console.log('associating ' + modelName);
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
/models/webhooktype.js
'use strict';
module.exports = function(sequelize, DataTypes) {
var WebhookType = sequelize.define('WebhookType', {
typeName: {
type: DataTypes.STRING,
allowNull: false,
field: 'type_name'
}
}, {
classMethods: {
associate: function(models) {
WebhookType.hasMany(models.WebhookUpdateLog, { foreignKey: 'webhookTypeId' });
}
},
timestamps: false,
tableName: 'webhook_types'
});
return WebhookType;
};
/models/webhookupdatelog.js
'use strict';
module.exports = function(sequelize, DataTypes) {
var WebhookUpdateLog = sequelize.define('WebhookUpdateLog', {
webhookTypeId: {
type: DataTypes.INTEGER,
allowNull: false,
field: 'webhook_type_id'
},
campaignId: {
type: DataTypes.INTEGER,
allowNull: false,
field: 'campaign_id'
},
responseJson: {
type: DataTypes.TEXT,
allowNull: false
}
}, {
classMethods: {
associate: function(models) {
WebhookUpdateLog.belongsTo(models.WebhookType, { foreignKey: 'webhookTypeId' });
WebhookUpdateLog.belongsTo(models.Campaign, { foreignKey: 'campaignId' });
}
},
timestamps: true,
updatedAt: false,
tableName: 'webhook_update_logs'
});
return WebhookUpdateLog;
};
via Franklin
No comments:
Post a Comment