Getting joined data from strongloop/loopback

江枫思渺然 提交于 2019-12-11 11:31:38

问题


How can I get data from two joined tables? Suppose, there are two models called Category (CategoryId, CategoryName) and Product(ProductId, ProductName, CategoryId), Is there a way to get a result like:(ProductId, ProductName, CategoryId, CategoryName)


回答1:


There should be a relation between your Category model and your Product model. A Category hasMany Products and each Product belongsTo a Category. So your model json files should be something like

Category:

{
  "name":"Category",
  "properties":{
    "CategoryId": {
      "type":"Number",
      "id":1
    },
    "CategoryName":{
      "type":"String"
    }
  },
  "relations": {
    "products": {
      "type":"hasMany",
      "model":"Product",
      "foreignKey":"CategoryId"
    }
  }
}

Product

{
  "name":"Product",
  "properties":{
    "ProductId: {
      "type":"Number",
      "id":1
    },
    "ProductName":{
      "type":"String"
    },
    "CategoryId": {
      "type":"Number"
    }
  },
  "relations": {
    "category": {
      "type":"belongsTo",
      "model":"Category",
      "foreignKey":"CategoryId"
    }
  }
}

Of course these json definitions must be completed with the corresponding options and datasource properties, which only you do know.

The relation between those two models will add endpoints to loopback explorer so you can query for products in a certan category:

GET /api/Categorys/:id_category/products

of the category to which a product belongs

GET /api/Products/:id_product/category

Please note that, unless you specify a plural option for Category, its plural will be Categorys. This is not a typo.

Finally, if you want to query for a product and its category, you would use the include filter

GET /api/Products/:id_product?filter[include]=category

hope it helps.



来源:https://stackoverflow.com/questions/30560735/getting-joined-data-from-strongloop-loopback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!