问题
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