Search code examples
node.jsloopbackjsloopback

How to get a master detail query by loopback?


I have Company and Product model with has many relation from company to product model. how to make a Get method to get company name or ID returns company information with all related products.

something like fallowing object:

 [{
        "C_name": "tatli",
        "address": "TR-IS- aktepe",
        "tel": "123456789",
        "id": "5a18772e61b6370e4c713b44",
      [{
    "P_Code": "123456",
    "P_name": "screw",
    "QTY": 30,
    "id": "5a1878af61b6370e4c713b46",
    "compny_id": "5a18772e61b6370e4c713b44"
  },
  {
    "P_Code": "123457",
    "P_name": "Bead",
    "QTY": 33,
    "id": "5a1878af61b6370e4c713b47",
    "compny_id": "5a18772e61b6370e4c713b44"
  }]
    }]

Solution

  • Hope you have provided the Relation properly in the model of Company . If not just look at the following link and Create the relation . In this case the relation will be a belongs to .

    Product Belongs to a Company

    In order to query the related results you have two ways .

    • Including it the default model of Company . So that loopback's default get will return you all the rows. Like

    company.json model file

      "relations": { // make sure the name of product model and foreign key is correct
        "product": {
          "type": "belongsTo",
          "model": "product",
          "foreignKey": "productId"
        }
      },
    
     "scope": {
        "include": "product"
      },
    
    • Second way is to write it in a remote method.
    Company.getPrefs = function(id, cb) {
        Company.find({
        where: {        
        },
        include: [{relation: 'Product'}]
    };