按嵌套数据环回 REST API 过滤器

Jan*_*szO 5 loopback filter loopbackjs

我想通过嵌套数据从 REST API 进行过滤。例如这个对象:

[
  {
    "name": "Handmade Soft Fish",
    "tags": "Rubber, Rubber, Salad",
    "categories": [
      {
        "name": "women",
        "id": 2,
        "parent_id": 0,
        "permalink": "/women"
      },
      {
        "name": "kids",
        "id": 3,
        "parent_id": 0,
        "permalink": "/kids"
      }
    ]
  },
  {
    "name": "Tasty Rubber Soap",
    "tags": "Granite, Granite, Chair",
    "categories": [
      {
        "name": "kids",
        "id": 3,
        "parent_id": 0,
        "permalink": "/kids"
      }
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

通过 GET 发送/api/products?filter[include]=categories ,我只想获取类别名称为“女性”的产品。这怎么办?

dun*_*n32 0

您能分享一下没有filter[include]=categorie 的情况吗?

[编辑]在评论中提出几个问题后,我将构建一个远程方法:在common/models/myModel.js(函数内部):

function getItems(filter, categorieIds = []) {
    return new Promise((resolve, reject) => {
        let newInclude;
        if (filter.hasOwnProperty(include)){
            if (Array.isArray(filter.include)) {
                newInclude = [].concat(filter.include, "categories")
            }else{
                if (filter.include.length > 0) {
                    newInclude = [].concat(filter.include, "categories");
                }else{
                    newInclude = "categories";
                }
            }
        }else{
            newInclude = "categories";
        }

        myModel.find(Object.assign({}, filter, {include: newInclude}))
        .then(data => {
            if (data.length <= 0) return resolve(data);
            if (categoriesIds.length <= 0) return resolve(data);

            // there goes your specific filter on categories
            const tmp = data.filter(
                item => item.categories.findIndex(
                    categorie => categorieIds.indexOf(categorie.id) > -1
                ) > -1
            );
            return resolve(tmp);
        })
    }
}
myModel.remoteMethod('getItems', {
    accepts: [{
        arg: "filter",
        type: "object",
        required: true
    }, {
        arg: "categorieIds",
        type: "array",
        required: true
    }],
    returns: {arg: 'getItems', type: 'array'}
});
Run Code Online (Sandbox Code Playgroud)

我希望它能回答你的问题...