从Strongloop/Loopback获取联接数据 [英] Getting joined data from strongloop/loopback
问题描述
如何从两个联接的表中获取数据? 假设有两个模型,分别称为Category(CategoryId,CategoryName)和Product(ProductId,ProductName,CategoryId),有没有一种方法可以得到如下结果:(ProductId,ProductName,CategoryId,CategoryName)
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)
推荐答案
您的类别"模型和产品"模型之间应该存在某种关系.类别有很多产品,每个产品属于一个类别.因此,您的模型json文件应该类似于
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
类别:
{
"name":"Category",
"properties":{
"CategoryId": {
"type":"Number",
"id":1
},
"CategoryName":{
"type":"String"
}
},
"relations": {
"products": {
"type":"hasMany",
"model":"Product",
"foreignKey":"CategoryId"
}
}
}
产品
{
"name":"Product",
"properties":{
"ProductId: {
"type":"Number",
"id":1
},
"ProductName":{
"type":"String"
},
"CategoryId": {
"type":"Number"
}
},
"relations": {
"category": {
"type":"belongsTo",
"model":"Category",
"foreignKey":"CategoryId"
}
}
}
当然,这些json定义必须使用相应的选项和数据源属性来完成,只有您确实知道.
Of course these json definitions must be completed with the corresponding options and datasource properties, which only you do know.
这两个模型之间的关系会将端点添加到回送资源管理器,以便您可以查询属于certan类别的产品:
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
产品所属类别的
GET /api/Products/:id_product/category
请注意,除非您为 Category 指定了复数选项,否则其复数将为 Categorys .这不是错字.
Please note that, unless you specify a plural option for Category, its plural will be Categorys. This is not a typo.
最后,如果要查询产品及其类别,则可以使用 include 过滤器
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
希望有帮助.
这篇关于从Strongloop/Loopback获取联接数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!