.related() docs are confusing or wrong
See original GitHub issueThe docs state:
The related method returns a specified relation loaded on the relations hash on the model, or calls the associated relation method and adds it to the relations hash if one exists and has not yet been loaded.
What this says to me is: “If the relations hash already has this relation loaded (.e.g .fetch({withRelated
), use that one. If it has not been loaded yet, then fetch()
it.”
Now, in my Express app, I have a route like:
router.get('/user/:id', auth, async (req, res, next) => {
let id = req.params.id, user, thingies
user = (id === 'me' || id === req.user.get('id'))
? req.user
: await User.where('id', id).fetch({withRelated: ['thingies'])
thingies = user.related('thingies')
})
When I hit the route using /user/2
, for example, it works fine. But if I hit /user/me
then thingies
is empty. This is because earlier, in the middleware where I set req.user
to be the authenticated user, I did not eager load the relation.
If I use .load()
it can fix it:
user = (id === 'me') ? req.user : await User.where('id', id).fetch({withRelated: ['thingies'])
user = await user.load('thingies')
thingies = user.related('thingies')
But this loses the potential benefit of eager loading dynamically only when necessary, which is how I interpreted the docs for .related()
. Am I wrong or is this a bug?
Issue Analytics
- State:
- Created 6 years ago
- Reactions:1
- Comments:5 (2 by maintainers)
Possibly related issues: #407, #711, #821 and #1018.
bump