如何在Strongloop中使用自连接创建父子层次结构。我已经创建了型号名称作为菜单。


  menu.json


{
  "name": "Menu",
  "base": "PersistedModel",
  "strict": false,
  "idInjection": false,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "MenuID": {
      "type": "Number",
      "id": true,
      "required": true
    },
    "Name": {
      "type": "string"
    },
    "ParentMenuID": {
      "type": "Number"
    }
  },
  "validations": [],
  "relations": {

    "menus": {
      "type": "hasMany",
      "model": "Menu",
      "foreignKey": "ParentMenuID",
    }
  },
  "acls": [],
  "methods": {}
}



  表数据如下:


menuId  Name     ParentID
1       parent      0
2       child       1
3      grandchild   2


我尝试使用过滤器进行REST API调用,但得到的是一级数据,例如
http://localhost:3000/api/Menus/?filter[include]=menus

 [
  {
    "MenuID": 1,
    "Name": "parent",
    "ParentMenuID": 0,
    "menus": [
      {
        "MenuID": 2,
        "Name": "child",
        "ParentMenuID": 1
      }
    ]
  },
  {
    "MenuID": 2,
    "Name": "child",
    "ParentMenuID": 1,
    "menus": [
      {
        "MenuID": 3,
        "Name": "grandchild",
        "ParentMenuID": 2
      }
    ]
  },
  {
    "MenuID": 3,
    "Name": "grandchild",
    "ParentMenuID": 2,
    "menus": []
  }
]


但是我需要像这样的输出:

[
  {
    "MenuID": 1,
    "Name": "parent",
    "ParentMenuID": 0,
    "menus": [
      {
        "MenuID": 2,
        "Name": "child",
        "ParentMenuID": 1,
        "menus": [
          {
            "MenuID": 3,
            "Name": "grandchild",
            "ParentMenuID": 2
          }
        ]
      }
    ]
  }
]


请提出任何想法或例子。

最佳答案

使用slc loopback:model创建模型后,只需运行slc loopback:relation并将自连接创建为关系。

就像您现在在更新的问题中所做的那样。要包含另一个级别,请使用include filterhttp://localhost:3000/api/Menus/?filter[include]=menus并包括两个级别,您可以这样做:http://localhost:3000/api/Menus/?filter[include][menus]=menus

10-08 08:19