loopbackio / loopbackio/loopback-datasource-juggler

Querying related models make unnecessary requests

Open
#1,796 7 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug good first issue LB3-only
Dominant language
JavaScript
Stars
282
Forks
366
Avg merge
17h 4m
Merged PRs (30d)
10

Description

## Steps to reproduce

Create a model called Book with the properties id,author,title
Add a hasMany relation between the default User model and the Book model using a through Model called UserToBook which has the following properties: userId,bookId

The relation is defined in the User model like so.
```json
"books": {
"type": "hasMany",
"model": "Book",
"foreignKey": "userId",
"through": "UserToBook",
"keyThrough": "bookId"
},
```

## Current Behavior

Querying the user for his books using a where filter performs 2 requests - one to the through model and one to the actual related model. The query to the through model is adding an `include` to the related model, which causes a fetch of a lot of data from the related model.
The reason this data is needed, is to extract the related model ids, so we can use it to filter out when performing the actual call the related model.

## Expected Behavior

There is no need at all to fetch the related model data in the first call - we can simply get the ids from the through model, and use them

## Link to reproduction sandbox

Working on it

## Additional information

Since I'm using (sadly) loopback 2.x I have added the fix to my own fork - https://github.com/regevbr/loopback-datasource-juggler/blob/2.x/lib/scope.js
You can understand and base the fix based on the changes there

https://github.com/regevbr/loopback-datasource-juggler/blob/2cf8269e41a153d01e4d505af586bad9bb9110dd/lib/scope.js#L100-L138

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading lib/scope.js, especially the behavior shown in the linked commit and the reported 2.x fork. Reproduce the hasMany-through query with a where filter and verify that the through-model request returns only related IDs without fetching full related-model data, while the final related-model query still applies the filter.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
backend, databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.