Joining two models in loopback using include filter

后端 未结 1 451
日久生厌
日久生厌 2021-01-15 02:07

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

相关标签:
1条回答
  • 2021-01-15 03:04

    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"]}
    
    0 讨论(0)
提交回复
热议问题