简体   繁体   中英

Loopback get a model related with hasMany

I have one model called subscription has a relation of hasMany with another model category .

How to fetch the models for a specific subscription.

Note: Not from API-explorer

What you should do is:

  • In common/models/subscription.json :

      { ... "relations": { "categories": { "type": "hasMany", "model": "Category", "foreignKey": "" } } } 
  • In common/models/category.json :

      { ... "relations": { "subscription": { "type": "belongsTo", "model": "Subscription", "foreignKey": "" } } } 

In REST (ie from API Explorer ) :

GET /Subscriptions?filter[include]=categories

In code (ie in a remote hook of : common/models/subscription.js ):

Subscription.find({include: 'categories'}, function (err, subscriptions) {
    console.log(subscriptions);
    //...
});

Well explained. F3L1X9. I want to add somethin here - whenever you add a hasMany relation one REST endpoint is created like

GET /Subscriptions/{id}/categories

which will give you the categories of the Subscription with the specified ID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM