Skip to content

Instantly share code, notes, and snippets.

@prule
Created October 5, 2014 09:32
Show Gist options
  • Save prule/be3bafe8903d6b18f4ef to your computer and use it in GitHub Desktop.
Save prule/be3bafe8903d6b18f4ef to your computer and use it in GitHub Desktop.
SequelizeJS many to many
// connect
var Sequelize = require("sequelize")
var sequelize = new Sequelize('spike', 'anon', 'password', {
logging: console.log
});
// models
var User = sequelize.define('User', {
name: Sequelize.STRING
});
var Project = sequelize.define('Project', {
name: Sequelize.STRING,
status: Sequelize.TEXT
});
// associations
Project.hasMany(User, { as: 'User', as: 'contributors' });
User.hasMany(Project, { as: 'contributors' });
// execute
sequelize.sync({force: true}).then(function () {
User.create({name: 'u1'}).then(function (user1) {
Project.create({name: 'p1'}).then(function (project1) {
user1.addContributor(project1).then(function () {
user1.getContributors().then(function (projects) {
console.log('User has '+projects.length+ ' projects');
})
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment