Skip to content

Instantly share code, notes, and snippets.

@mbenedettini
Created September 15, 2018 15:29
Show Gist options
  • Save mbenedettini/0c2ae3204e12f4ed939fc2a588e8497f to your computer and use it in GitHub Desktop.
Save mbenedettini/0c2ae3204e12f4ed939fc2a588e8497f to your computer and use it in GitHub Desktop.
Loopback relations: querying relations with/without include
/* Previously defined in customer-user.json:
"relations": {
"roles": {
"type": "hasMany",
"model": "Role",
"foreignKey": "principalId",
"through": "RoleMapping"
}
},
*/
let user = await CustomerUser.findById(userId);
logger.debug(user.roles);
// object with querying functions that return a promise: find, create, count, findAll, etc
logger.debug(user.roles());
// undefined
logger.debug(await user.roles.find());
// promise that resolves to all roles associated with user
// Now, same queries, but this time including roles
let user = await CustomerUser.findById(userId, {
include: 'roles'
});
logger.debug(user.roles);
// object with querying functions that return a promise: find, create, count, findAll, etc
logger.debug(user.roles());
// roles associated with user
logger.debug(await user.roles.find());
// promise that resolves to all roles associated with user
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment