Best way to query a Many to Many Relationship using pg-promise
<p>For example I want to get the user info, emails and it's roles from db and create an object like :</p>

<pre><code>{
  "id": 1,
  "firstname": "John",
  "lastname": "Johnny",
  "emails": [
    {
      "type": "work",
      "email": "work@work.com"
    },
    {
      "type": "personal",
      "email": "personal@personal.com"
    }
  ],
  "roles": [
    {
      "role": "ADM",
      "title": "Admin"
    },
    {
      "role": "PUB",
      "title": "Publisher"
    }
  ]
}
</code></pre>

<p>There are three tables I need to query:</p>

<ul>
<li><code>Users</code> table has <code>id</code>, <code>firstname</code>,<code>lastname</code>.</li>
<li><code>Emails</code> table has <code>type</code>, <code>email</code>,<code>user_id</code>.</li>
<li><code>Roles</code> table has <code>role</code>, <code>title</code>,<code>user_id</code>.</li>
</ul>

<p>Based on the <a href="https://github.com/vitaly-t/pg-promise" rel="nofollow">pg-promise</a>'s wiki I am almost sure it has to be done using <a href="https://github.com/vitaly-t/pg-promise/wiki/Learn-by-Example#tasks" rel="nofollow">Tasks</a> but not sure how would you chain them. </p>

<p><strong>UPDATE</strong> In my actual project I had to insert a product and use the generated id to insert attributes. Adding my code here in case you have a similar situation:</p>

<pre><code>//Insert a new product with attribites as key value pairs
post_product_with_attr: function(args) {
    return db.task(function(t) {
        return t.one(sql.post_new_product, args)
            .then(function(dt) {
                var queries = [];
                Object.keys(args).forEach(function(key) {
                    queries.push(t.one(sql.post_attr_one, { Id: dt.id, key: key, value: args[key] }));
                 });
                return queries.length ? t.batch(queries) : [dt];
            });
    });
}
</code></pre>