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

如何在Strapi查询中筛选localizations字段的指定属性

解决Strapi查询localizations字段的需求

要实现仅返回指定locale(ka)的条目,无匹配时取第一条,且只保留locale属性,你可以通过Strapi的过滤、字段选择结合API参数直接实现,无需前端二次处理:

1. 直接通过API参数实现过滤与字段限制

在原查询URL基础上添加过滤条件、字段限制和结果条数控制:

{{strapiUrl}}/products/2?populate[localizations][filters][locale][$eq]=ka&populate[localizations][fields][0]=locale&populate[localizations][limit]=1

参数说明:

  • populate[localizations][filters][locale][$eq]=ka:过滤出locale等于ka的localizations条目
  • populate[localizations][fields][0]=locale:仅保留locale属性,剔除其他冗余字段
  • populate[localizations][limit]=1:限制仅返回一条结果

2. 无匹配时自动取第一条的补充方案

如果Strapi默认在无匹配结果时不会返回localizations字段,你可以通过自定义控制器实现 fallback 逻辑:

在src/api/product/controllers/product.js中修改findOne方法:

async findOne(ctx) {
  const { id } = ctx.params;
  // 优先查询locale为ka的条目
  const targetProduct = await strapi.db.query('api::product.product').findOne({
    where: { id },
    populate: {
      localizations: {
        filters: { locale: 'ka' },
        fields: ['locale'],
        limit: 1
      }
    }
  });

  // 无匹配时取第一条localizations
  if (!targetProduct.localizations.length) {
    const fallbackProduct = await strapi.db.query('api::product.product').findOne({
      where: { id },
      populate: {
        localizations: {
          fields: ['locale'],
          limit: 1
        }
      }
    });
    return fallbackProduct;
  }

  return targetProduct;
}

修改后前端调用原接口{{strapiUrl}}/products/2即可直接得到符合要求的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 05:42:03