Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 253
IvanZh Avatar asked Nov 18 '14 15:11

IvanZh


People also ask

What is persisted model in LoopBack?

PersistedModel is the base class for models connected to persistent data sources such as databases and is also the base class for all built-in models (except Email). It provides all the standard create, read, update, and delete (CRUD) operations and exposes REST endpoints for them.


2 Answers

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

filter: {
 include:{
  relation: "users",
  scope: {
   fields:["name"]
  }
 }
}
like image 136
Hidde Stokvis Avatar answered Oct 25 '22 03:10

Hidde Stokvis


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.

like image 45
Alex V Avatar answered Oct 25 '22 02:10

Alex V