Loopback 2.4: how to query certain fields of related model via REST API
Asked Answered
C

3

5

I have User model over relational DB.

Each User can hasMany "users" where "chiefId" is FK.

"relations": {
    "users": {
      "type": "hasMany",
      "model": "User",
      "foreignKey": "chiefId"
    },
}

I can query related users for each chief-user like this:

GET /users?filter={"include":"users"}

But it returns full user objects.

  • How should I query only "name" properties of related users?
  • Also is it possible to count related instances in one request to server?
Corselet answered 18/11, 2014 at 15:1 Comment(1)
not supported it seems, see #25904485Irvingirwin
D
8

A late reply but I just ran into this question now. It is possible:

filter: {
 include:{
  relation: "users",
  scope: {
   fields:["name"]
  }
 }
}
Dash answered 21/8, 2015 at 8:39 Comment(2)
Is this part of the model?Dehydrate
@Dehydrate Look at include filter docsPashm
C
2

As far as I understood this question is about adding a nested filter on an include level, which seems to be not yet supported: https://groups.google.com/forum/#!msg/loopbackjs/T6onsYMJFOI/V4ILc3Obf3MJ

May be it's not the best way to approach this problem, but what you can do is a manual response transformation in .afterRemote('find', ...) hook.

Celestinacelestine answered 19/11, 2014 at 22:36 Comment(0)
I
0
/users?filter[fields][0]=name

See https://github.com/strongloop/loopback-example-relations-basic for more info.

Irvingirwin answered 18/11, 2014 at 18:20 Comment(3)
This doesn't work for included objects. And I need only "name" for related (or embedded) user objects!Corselet
do any of use cases in the example repo meet your use case? maybe this one /api/customers?filter[include][reviews]=author&filter[where][age]=21Irvingirwin
I saw the use cases, but they don't limit fields returned from relation. As Alex Voitau said, this isn't supported yet. Nevertheless thanks for response!Corselet

© 2022 - 2024 — McMap. All rights reserved.