Last active
June 16, 2016 22:39
-
-
Save DesignByOnyx/1c8e61f46312d29d62d6 to your computer and use it in GitHub Desktop.
Adjust feathersjs with sequelize to allow models to set up relationships
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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, | |
... | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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