Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sequelize Associations

File Structure:

  • seed_database.js
  • config.json
  • models/
    • index.js
    • User.js
    • UserType.js

Make sure that the SQL configs are in config.json.

$ node seed_database.js

It's important to node that the models/User.js contains an associate function. Read more at: http://sequelizejs.com/articles/express#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('../config.json')[env];
var sequelize = new Sequelize(config.database, config.username, config.password, config);
var db = {};
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf(".") !== 0) && (file !== basename);
})
.forEach(function(file) {
var model = sequelize["import"](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if ("associate" in db[modelName]) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
var Sequelize = require('sequelize');
var env = process.NODE_ENV || 'development';
var config = require('./config.json')[env];
// Connect to the database
var sequelize = new Sequelize(config.database, config.username, config.password, config);
// Import models
var models = require('./models');
// http://runnable.com/UXgrne_v2oZyAACN/how-to-use-associations-in-sequelize-for-node-js
var chainer = new Sequelize.Utils.QueryChainer;
var admin, adminUserType;
models.sequelize.sync({force: true})
.then(function() {
/**
* We want to call `build` instead of `create`
* since `create` invokes `build` and `save`.
* We want to `save` AFTER dependencies are created.
*/
// Build the instances (do not invoke save yet!)
admin = models.User.build({
username: 'Admin',
password: 'p@$$w0rd'
});
// Build the instances (do not invoke save yet!)
adminUserType = models.UserType.build({
role: 'administrator'
});
// Explicitly state how the rows should be saved.
chainer
.add(adminUserType.save())
.add(admin.save());
// Execute everything in the chainer
chainer.run()
//On success, set the user
.on('success', function() {
// Set the userType
admin.setUserType(adminUserType);
});
})
'use strict';
/**
* Customer Address table for 1 to many relationship for a
* customer having multiple addresses
* @param {Object} sequelize Sequelize instance
* @param {Object} DataTypes DataTypes enum
* @return {Object} User definition object
*/
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('User', {
id: {
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true,
isInt: true
},
username: {
type: DataTypes.STRING,
allowNull: false
},
password: {
type: DataTypes.STRING,
allowNull: false
}
}, {
classMethods: {
// Creates an association function that is run AFTER all the models are loaded into sequelize.
associate: function (models) {
User.belongsTo(models.UserType);
}
}
});
return User;
}
'use strict';
/**
* Customer Address table for 1 to many relationship for a
* customer having multiple addresses
* @param {Object} sequelize Sequelize instance
* @param {Object} DataTypes DataTypes enum
* @return {Object} User definition object
*/
module.exports = function(sequelize, DataTypes) {
var UserType = sequelize.define('UserType', {
id: {
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true,
isInt: true
},
role: {
type: DataTypes.STRING,
allowNull: false
}
});
return UserType;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment