使用包含过滤器在环回中加入两个模型 [英] Joining two models in loopback using include filter
问题描述
我有两个型号的购买和产品,而且productId对两者都很常见。
I have two models Purchase and Products, and productId is common for both.
我需要从productId的产品型号中找到productDetails。
I need to find the productDetails from product model for a purchaseId.
所以我在Purchase模型中创建了一个名为getProductDetails的自定义端点。
So I have created a custom endpoint in Purchase model, called getProductDetails.
这就是我试图查询模型的方法。
This is how I am trying to query the models.
Purchase.find({
"filter": {
include: {
relation: 'Product',
scope: {
fields: ['productDesc'],
}
}
},
where:{
id:purchaseId
},
我的关系是
购买belongsTo产品,foreignKey是productId
My relation is Purchase belongsTo Product, foreignKey being productId
产品有很多购买
但即使我做上述查询,我也是不要在查询结果中获得productDesc
我的模型关系是否错误?
推荐答案
假设产品和购买模型定义如下:
Assuming Product and Purchase models defined as follows:
product.json
product.json
{
"name": "Product",
"base": "PersistedModel",
"idInjection": true,
"properties": {
"productDesc": {
"type": "string",
"required": false
}
},
"validations": [],
"relations": {
"purchases": {
"type": "hasMany",
"model": "Purchase",
"foreignKey": "productId"
}
},
"acls": [],
"methods": {}
}
purchase.json
purchase.json
{
"name": "Purchase",
"base": "PersistedModel",
"idInjection": true,
"properties": {},
"validations": [],
"relations": {
"product": {
"type": "belongsTo",
"model": "Product",
"foreignKey": "productId"
}
},
"acls": [],
"methods": {}
}
我已经调整了你的查询:
I have adjusted your query like this:
let product = await Purchase.find({
include: {
relation: 'product',
scope: {
fields: ['productDesc']
}
},
where: {
id: 1
}
})
注意:使用ES6和ES7,但可以很容易地重写为ES5
Note: ES6 and ES7 used, but it can be easily rewriten to ES5
您必须使用 toJSON 转换返回的模型将相关项放入普通JSON对象的实例。
You have to use toJSON to convert the returned model instance with related items into a plain JSON object.
我不确定,为什么要创建新端点。环回提供的应该足够了。
I'm not sure, why are you creating a new endpoint though. The ones provided by loopback should be sufficient.
例如
GET /Purchases/{id}/product
或
GET /Purchases/{id}
带过滤器
{ "include": [ "product"]}
这篇关于使用包含过滤器在环回中加入两个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!