public
Last active

Sequelize associated data many-many

  • Download Gist
sequelize-include.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
 
// 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;
};

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.