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

Strapi中如何使用find方法查询JSON类型字段的嵌套属性匹配内容

Strapi JSON字段嵌套属性查询解决方案

问题根因

你当前的写法会被Strapi默认解析为完全匹配整个user字段的值,也就是仅能匹配user字段恰好等于{"id":"传入参数"}的内容,和你实际存储的包含name属性的JSON结构不符,因此返回空数组。

不同版本的实现方式

Strapi v4 版本

使用官方推荐的entityService进行查询,直接在filters中声明嵌套属性即可:

async findByUser(ctx) {
  const userId = ctx.params.id;
  const blogs = await strapi.entityService.findMany('api::blog.blog', {
    filters: {
      user: {
        id: userId
      }
    }
  });
  return blogs;
}

如果上述写法在你的数据库中不生效,可以使用原生查询兜底:

  • PostgreSQL 数据库示例:
async findByUser(ctx) {
  const userId = ctx.params.id;
  const result = await strapi.db.connection.raw(
    `SELECT * FROM blogs WHERE (user->>'id') = ?`,
    [userId]
  );
  return result.rows;
}
  • MySQL 数据库示例:
async findByUser(ctx) {
  const userId = ctx.params.id;
  const result = await strapi.db.connection.raw(
    `SELECT * FROM blogs WHERE JSON_UNQUOTE(JSON_EXTRACT(user, '$.id')) = ?`,
    [userId]
  );
  return result[0];
}

Strapi v3 版本

直接使用属性路径作为查询键即可:

async findByUser(ctx) {
  const blogs = await strapi.query('blogs').find({
    'user.id': ctx.params.id
  });
  return blogs;
}

注:MongoDB数据库对JSON嵌套属性的查询支持度最高,上述所有版本的键路径写法都可以直接生效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:45:00