I have two models Purchase and Products, and productId is common for both.
I need to find the productDetails from product model for a purchaseId.
So I have c
Assuming Product and Purchase models defined as follows:
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
{
"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
}
})
Note: ES6 and ES7 used, but it can be easily rewriten to ES5
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.
e.g.
GET /Purchases/{id}/product
or
GET /Purchases/{id}
with filter
{ "include": [ "product"]}