Created
October 5, 2014 09:32
-
-
Save prule/be3bafe8903d6b18f4ef to your computer and use it in GitHub Desktop.
SequelizeJS many to many
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
// 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