环回关系

时间:2018-07-20 10:13:41

标签: node.js loopbackjs

如何进行关系以与回送中的数据数组匹配

例如

我的模特

 // 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": {}
}

预期输出:

  

[         {           “ title”:“地区1”,           “ field_images”:[{                “ name”:“图片2”,                “ url”:“ /media/image-1600x650.jpg”,             },{                “ name”:“图片1”,                “ url”:“ /media/image-1600x650.jpg”,             }]       }]

1 个答案:

答案 0 :(得分:0)

假设关系是HasMany

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

两个模型之间定义了一种关系。因此,我非常怀疑您是否会将图像保存在数组中(如果要定义它们之间的关系)。

但是在环回时,您可以使用单独的API来检索field_images,而不是将其作为数组获取。

例如-您可以像这样检索图像

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