You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Strapi V4中对数组类型属性使用$in查询?

问题

需要对数组类型的categories属性应用$in查询,但当前实现方式不正确,寻求解决方案。

错误的查询示例

where: {
   $and: [
     categories: {
       name: {
         $in:["fire"],
       },
     },
   ]
},

待完善的查询代码

const entries = await strapi.db
  .query("api::data.data")
  .findMany({
    populate: ["*"],
    orderBy: "id",
    where: {} // 需要填充正确的查询条件
});

数据条目示例

{
  "id": 1,
  "description": "....",
  "categories": [
    {"id": 1, "name": "fire"},
    {"id": 2, "name": "water"}
  ]
}
解决方案

在Strapi的查询语法中,针对包含对象的数组字段(如categories),要筛选数组中至少有一个元素的name匹配$in列表值的条目,直接在where中嵌套字段条件即可,无需多余的$and包裹(仅当存在多个并行条件时才需要$and)。

正确的单条件查询代码

const entries = await strapi.db
  .query("api::data.data")
  .findMany({
    populate: ["*"],
    orderBy: "id",
    where: {
      categories: {
        name: {
          $in: ["fire"]
        }
      }
    }
});

多条件场景示例

如果需要同时满足多个查询条件,再用$and包裹:

const entries = await strapi.db
  .query("api::data.data")
  .findMany({
    populate: ["*"],
    orderBy: "id",
    where: {
      $and: [
        { categories: { name: { $in: ["fire"] } } },
        { description: { $contains: "测试内容" } } // 示例附加条件
      ]
    }
});

内容的提问来源于stack exchange,提问作者Chris Michael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 06:15:19