Loop through results and run another query for each result... Best practice?

1,880 views
Skip to first unread message

jo...@lennd.com

unread,
Aug 16, 2013, 11:42:10 AM8/16/13
to sequ...@googlegroups.com
Hey all. I'm having trouble looping through a results set and then running another query for each result in order to attach some additional data. 

Below is my code. "Pages" is a result from a Sequelize query. For each page, I'm trying to attach it's respective mentions. What's the best practice here?

Oddly, the below code actually renders the association to my view on localhost. But when pushed to Heroku, it does not.

  1. // pages == an object    
  2.     // for each page, get mentions
  3.    for(var k in pages) {
  4.       // build query
  5.      var query = 'SELECT m.url, b.name, b.icon_path FROM "Page_has_Mentions" h ';
  6.          query +='join "Mentions" m on m.id = h.mention_id ';
  7.          query +='join "Blogs" b on b.id = m.blog_id ';
  8.          query +='where h.page_id = \'' + pages[k].id + '\'';
  9.       // get and attach mentions
  10.      global.db.sequelize.query(query)
  11.      .success(function(mentions) {
  12.        pages[k].mentions = mentions;
  13.      });
  14.     }


jo...@lennd.com

unread,
Aug 16, 2013, 7:28:15 PM8/16/13
to sequ...@googlegroups.com
Solved this using a tip from the user Duranga via Github: 

Querychainer for the win.

Gary John

unread,
May 20, 2014, 3:27:45 PM5/20/14
to sequ...@googlegroups.com, jo...@lennd.com
Can you please post a snippet how you achieved looping through the results using QueryChainer? I'm facing this same issue, but I'm not sure I'm using QueryChainer correctly. TIA!

Sascha Depold

unread,
May 21, 2014, 1:31:51 AM5/21/14
to Gary John, sequ...@googlegroups.com, jo...@lennd.com
You basically just have to put stuff into the chainer, run it und iterate over the results:

Example: You have a User with a name and Posts with text. When a Post’s text starts with the name of the User, it is related to him:

User.all().success(function(users) { 
  var q = new Sequelize.Utils.QueryChainer(); 
  users.forEach(function(u) { 
    q.add(Post.findAll({ where: ["`text` LIKE '" + u.name + "%'"] })); 
  });
  q.run().success(function(results) { 
    console.log("Posts of the user "+users[0].name+":", results[0].map(function(p) { return p.values })) 
    console.log("Posts of the user "+users[1].name+":", results[1].map(function(p) { return p.values })) 
  }) 
})

Mick Hansen

unread,
May 21, 2014, 3:14:03 AM5/21/14
to Sascha Depold, Gary John, sequ...@googlegroups.com, jo...@lennd.com
I would suggest using promises going forward.
Sequelize as a project is moving away from the QueryChainer internally.
--
Mick Hansen
@mhansendev
mhansen.io
Reply all
Reply to author
Forward
0 new messages