0
votes

How to do the relation to match with an array of data in loopback

For e.g

My Models

 // Regions model  
{
      "name": "regions",
      "base": "PersistedModel",
      "idInjection": true,
      "options": {
        "validateUpsert": true
      },
      "properties": {
        "title": {
          "type": "string",
          "required": true
        },
        "images": {
          "type": [
            {
              "target_id": {
                "type": "string"
              }
            }
          ]
        },
      },
      "validations": [],
      "relations": {},
      "acls": [],
      "methods": {}
    }

    // Images model
{
  "name": "images",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "name": {
      "type": "string",
      "required": true
    },
    "url": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": { },
  "acls": [],
  "methods": {}
}

Expected output:

[ { "title": "Region 1", "field_images": [{ "name": "Image 2", "url": "/media/image-1600x650.jpg", },{ "name": "Image 1", "url": "/media/image-1600x650.jpg", }] } ]

1
What would the model relation be? Each region has many images? - Sashi
@Sashi, yes each region has many images - Rahul Radhakrishnan
Did you get a chance to try what I suggested in the answer? - Sashi

1 Answers

0
votes

Assuming that the relationship is HasMany

{
  "name": "regions",
  "base": "PersistedModel",
  ...
  "relations": {
    "images": {
      "type": "hasMany",
      "model": "images",
      "foreignKey": "title", //region title
    }
  }
  ...
}

A relationship is defined between two models. So, I highly doubt you would get the images inside an array (if you want to define a relationship between them).

But on loopback you can use separate APIs to retrieve the field_images instead of getting it as an array.

For example - you could retrieve the images like this

region.images([filter],
  function(err, images) {
  ...
});