How to include related objects in REST with loopback.io

I use the loopback tool for Strongloop to create a REST service. I am wondering how to determine which related objects are returned when a model is requested.

In the docs, I see that you can send a request like GET /api/members?filter[include]=posts and it will return the associated message models, and I found that you can make a request like GET /api/members?filter[include]=posts&filter[include]=comments , to receive posts and comments, but is there a way to determine, either in the code or in the generated json file, that you want a specific relation to always be returned when a model is requested?

+2
source share
2 answers

The properties of the specified filter are named by default. We have a pending transfer request to support this. See https://github.com/strongloop/loopback-datasource-juggler/pull/296 .

As a workaround before releasing the function, you can use hook to Remote to update the default filter object. See http://docs.strongloop.com/display/LB/Defining+remote+hooks .

+1
source

You can use two different simple methods to get links to your account.

  • Using model definitions in the Model.json file.

     "validations": [], "relations": { "team": { "type": "belongsTo", "model": "Team", "foreignKey": "" }, "user": { "type": "belongsTo", "model": "User", "foreignKey": "" } } 

This always connects one model with other models using direct relationships, and you can get them using the following lines of code.

 app.models.TeamRole.findOne({ where: { userId: user.id }, include:[ { relation: 'team' }, { relation: 'user' } ] },function(err,team,user){ //retrieve relational data here }); 
  1. You can use operational hooks to easily get these kinds of relationships.

Greetings.

+1
source

Source: https://habr.com/ru/post/983927/


All Articles