Created
September 15, 2018 15:29
-
-
Save mbenedettini/0c2ae3204e12f4ed939fc2a588e8497f to your computer and use it in GitHub Desktop.
Loopback relations: querying relations with/without include
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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