Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@whito
Created November 29, 2012 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whito/4170178 to your computer and use it in GitHub Desktop.
Save whito/4170178 to your computer and use it in GitHub Desktop.
Sequelize associated data many-many
// Simple example where you have a many-many relationship with Categories and Posts
// in sequelizejs and want to send the associated data as part of the response
Category.findAll({include: ['posts'] })
.success(function(categories) {
var results = categories.map(function(category) {
var temp = mapAttributes(category);
var p_results = category.posts.map(function(post){
var t = mapAttributes(post);
return t;
});
temp.posts = p_results;
return temp;
});
// this is for an expressjs app to send the results as json
response.json(results);
});
function mapAttributes(instance) {
var obj = new Object(),
ctx = instance;
ctx.attributes.forEach(function(attr) {
//console.log(attr);
obj[attr] = ctx[attr];
});
return obj;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment