Joining two models in loopback using include filter

懵懂的女人 提交于 2019-12-30 11:05:13

问题


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 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
            },

My relation is Purchase belongsTo Product, foreignKey being productId

Product hasMany Purchase

But even when I do the above query, I do not get productDesc in query result

Is my model relation wrong ?


回答1:


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"]}


来源:https://stackoverflow.com/questions/36899067/joining-two-models-in-loopback-using-include-filter

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