Skip to content

Instantly share code, notes, and snippets.

@prule
Created October 5, 2014 10:23
Show Gist options
  • Save prule/df358a06b6a5847a33e5 to your computer and use it in GitHub Desktop.
Save prule/df358a06b6a5847a33e5 to your computer and use it in GitHub Desktop.
SequelizeJS many to many - part 2
/**
* create database spike;
* grant all privileges on spike.* to 'anon'@'localhost' identified by 'password';
* flush privileges;
*/
var async = require('async');
// set up sequelize
var Sequelize = require("sequelize");
var sequelize = new Sequelize('spike', 'anon', 'password', {
logging: console.log
});
var User = sequelize.define('User', {
name: Sequelize.STRING
});
// set up our models
var Project = sequelize.define('Project', {
name: Sequelize.STRING,
status: Sequelize.TEXT
});
Project.hasMany(User, { as: 'User', as: 'contributors' });
User.hasMany(Project, { as: 'contributors' });
async.waterfall([
// create tables
function (next) {
return sequelize.sync({force: true}).then(function () {
next();
});
},
// insert users
function (next) {
return User.create({name: 'u1'}).then(function (u1) {
User.create({name: 'u2'}).then(function (u2) {
User.create({name: 'u3'}).then(function (u3) {
next(null, u1, u2, u3);
});
});
});
},
// insert projects
function (u1, u2, u3, next) {
return Project.create({name: 'p1'}).then(function (p1) {
Project.create({name: 'p2'}).then(function (p2) {
Project.create({name: 'p3'}).then(function (p3) {
next(null, u1, u2, u3, p1, p2, p3);
});
});
});
},
// associate users and projects
function (u1, u2, u3, p1, p2, p3, next) {
return u1.setContributors([p1, p2, p3]).then(function () {
u2.setContributors([p1, p3]).then(function () {
u3.addContributor(p2).then(function () {
next(null, u1, u2, u3, p1, p2, p3);
});
});
});
},
// run some queries
function (u1, u2, u3, p1, p2, p3, next) {
u1.getContributors({where: {name: 'p1'}}).then(function (projects) {
console.log('User 1 has ' + projects.length + ' projects named p1');
});
p2.getContributors({where: {name: 'u1'}}).then(function (users) {
console.log('Project 2 has ' + users.length + ' user named u1');
});
p2.getContributors({where: {name: { like: 'u%'}}}).then(function (users) {
console.log('Project 2 has ' + users.length + ' users named like u%');
});
}
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment