Javascript Strapi上的Graphql过滤器使用;其中;方法检查记录是否包含空数组
有人知道如何使用graphql“where”过滤器方法检查数组是否包含任何项吗? 目前,我使用以下查询:Javascript Strapi上的Graphql过滤器使用;其中;方法检查记录是否包含空数组,javascript,graphql,strapi,Javascript,Graphql,Strapi,有人知道如何使用graphql“where”过滤器方法检查数组是否包含任何项吗? 目前,我使用以下查询: query devices { onts(where:{images_null: false}){ id images{ id } } } 返回: { "data": { "onts": [ { "id": "5ebfffa957c09c029fa7831c", "images": [
query devices {
onts(where:{images_null: false}){
id
images{
id
}
}
}
返回:
{
"data": {
"onts": [
{
"id": "5ebfffa957c09c029fa7831c",
"images": [
{
"id": "5ed3a5040889c464b4e5e07f"
}
]
},
{
"id": "5eccc3bb7c3b9d59351593de",
"images": []
},
{
"id": "5ece135e7c3b9d59351593df",
"images": []
}
]
}
}
如您所见,2倍的返回记录包含空数组。我希望查询只返回数组中至少包含一项的记录 使用StrapiV3.0.1
感谢您的帮助 目前似乎对数组字段的过滤没有很好地实现: 但是,有一个变通方法供您尝试 首先,您应该知道如何在Strapi上编写自己的GraphQL
Resolver
:
下面是一个简单的解决方法,您可以尝试以下代码(假设您的模型是ont
):
请注意,如果您需要更复杂的实现,如分页和排序,则需要类似于strapi.model
的东西来使用底层ORMAPI:
您的代码如下所示(以mongodb为例)
希望它能帮助你~ 谢谢!实际上,我最终做了一件非常类似于您建议的事情,即构建一个自定义控制器。我很喜欢你的排序解决方案,可能只是抓住了这个宝贵的代码块!
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)
}
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
}