Strapi 上的 Graphql 过滤器使用 "where" 方法检查记录是否包含空数组

Graphql Filter on Strapi using the "where" method to check if a record contain empty array

有谁知道如何使用 graphql “where” 过滤方法来检查数组是否包含任何项目? 目前,我使用以下查询:

query devices {
  onts(where:{images_null: false}){
    id
    images{
      id
    }
  }
}

其中 return 个:

{
  "data": {
    "onts": [
      {
        "id": "5ebfffa957c09c029fa7831c",
        "images": [
          {
            "id": "5ed3a5040889c464b4e5e07f"
          }
        ]
      },
      {
        "id": "5eccc3bb7c3b9d59351593de",
        "images": []
      },
      {
        "id": "5ece135e7c3b9d59351593df",
        "images": []
      }
    ]
  }
}

如您所见,2x returned 记录包含空数组。
我希望查询仅包含数组中至少一项的 return 记录。

使用 Strapi v 3.0.1

感谢任何帮助。

目前似乎对数组字段的过滤没有很好地实现:

https://github.com/strapi/strapi/discussions/6480#discussioncomment-61022

但是,您可以尝试一种解决方法。

首先你应该知道如何在 Strapi:

上编写你自己的 GraphQL Resolver

https://strapi.io/documentation/v3.x/plugins/graphql.html#customize-the-graphql-schema

那么这里有一个简单的解决方法,您可以尝试以下代码(假设您的型号是 ont):

resolver: async (obj, options, ctx) => {
  // Get all onts first
  const onts = await strapi.api.onts.services.onts.find()

  // Filter your result
  return onts.filter(ont => ont.images.length > 0)
}

请注意,如果您需要更复杂的实现,例如分页和排序,您将需要类似 strapi.model 的东西来使用底层 ORM api:

你的代码看起来像这样(以 mongodb 为例)

resolver: async (obj, options, {context}) => {
  const {_start, _limit, _sort} = context  

  // Get your 'onts' from database
  const onts = await strapi.query('ont').model.aggregate([{
        $lookup: {
            from: "ont",
            localField: "_id",
            foreignField: "ont",
            as: "images"
        }
    }, {
        $match: {
            // Your filter here, same as image.length > 0
            'images.0': {$exists:true}
        }
    }, {
        $sort: {_sort}
    }, {
        $skip: parseInt(_start)
    }, {
        $limit: parseInt(_limit)
    }])

  return onts
}

希望对你有所帮助~!