Search code examples
loopbackjs

Loopback send relation data on request


In loopback we have model relationships. Here is an example model

{
  id: "gdfgd",
  name: "companyname",
  ownerId: "userId",
}

When requesting with get endpoint the response is like that.

But is there anyway to make loopback resolve those ids and send back the actual user data embedded inside the response?

Something like this

    {
      id: "gdfgd",
      name: "companyname",
      ownerId: {
        id: "hhrtgrt",
        username: "username",
        email: "[email protected]"
      },
    }

Solution

  • You should check the docs (include relations) about the relations in loopback, especially include filter. You can include a relationship in your request, for example, if you have a List model and a Task model, then you can have Task belongsTo List relationship and List hasMany Task relationship. You can check how to define those relationships in docs (relations) as well.

    // model: List 
    ...
    "relations":  {
      "tasks": {
        "type": "hasMany",
        "model": "Task",
        "foreignKey": ""
      }
    }
    
    // model: Task
    ...
    "relations":  {
      "list": {
        "type": "belongsTo",
        "model": "List",
        "foreignKey": ""
      }
    }
    

    When you define your relationships between models correctly, your GET request then could look like this:

    localhost:3000/api/List?filter[include]='tasks'  // get all lists with all tasks - each list will have all its tasks
    

    Or

    localhost:3000/api/Task?filter[include]='list'  // get all tasks with their list - each task will have its parent list
    

    In general, loopback doc is a great place to start the journey, they give a lot of examples and describe it pretty well.