Skip to content

Instantly share code, notes, and snippets.

@DesignByOnyx
Last active June 16, 2016 22:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save DesignByOnyx/1c8e61f46312d29d62d6 to your computer and use it in GitHub Desktop.
Save DesignByOnyx/1c8e61f46312d29d62d6 to your computer and use it in GitHub Desktop.
Adjust feathersjs with sequelize to allow models to set up relationships
// Only showing relevant changes
// The folllowing changes must be made in all of your models
var Author = sequelize.define('Authors', {
...
}, {
classMethods: {
// Create a static 'associate' method - will be called later
associate: function (models) {
Author.hasMany(models.Books, { as: 'books' });
}
}
});
// Syncing is done elsewhere - don't do it here
// Author.sync();
// Only showing relevant changes
// The following changes must be made in all of your services
// No need to import your model any more
// const Author = require('./author');
module.exports = function(){
const app = this;
// reference your model this way
const models = app.get('models');
const options = {
Model: models.Authors,
...
}
};
// Only showing relevent changes
const path = require('path');
module.exports = function() {
...
app.set('sequelize', sequelize);
app.set('models', associateModels(sequelize));
sequelize.sync();
...
};
function associateModels (sequelize) {
var models = {};
['author', 'book'].forEach(function(modelName) {
var model = sequelize.import(path.join(__dirname, './' + modelName + '/' + modelName + '-model'));
models[model.name] = model;
});
Object.keys(models).forEach(function(modelName) {
if ("associate" in models[modelName]) {
models[modelName].associate(models);
}
});
return models;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment