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

如何用gatsby-transformer-json自定义GraphQL Schema关联位置与文章JSON数据?

解决Gatsby中JSON数据的GraphQL关联查询问题

我之前也遇到过类似的问题,刚好可以帮你搞定这个JSON数据关联的需求~核心是通过Gatsby的createSchemaCustomization API自定义GraphQL Schema,让它识别到locations里的posts字段应该关联到对应的文章对象列表。

先确认你的JSON结构(参考示例)

假设你的两个JSON文件结构大概是这样的:

  • locations.json(每个位置包含关联的文章ID数组)
[
  {
    "id": "loc_001",
    "name": "上海",
    "posts": ["post_001", "post_002"]
  },
  {
    "id": "loc_002",
    "name": "广州",
    "posts": ["post_003"]
  }
]
  • posts.json(每篇文章有唯一ID)
[
  {
    "id": "post_001",
    "title": "上海外滩游玩攻略",
    "content": "..."
  },
  {
    "id": "post_002",
    "title": "上海本帮菜探店指南",
    "content": "..."
  },
  {
    "id": "post_003",
    "title": "广州早茶全攻略",
    "content": "..."
  }
]

步骤1:在gatsby-node.js中自定义Schema

在项目根目录的gatsby-node.js文件里添加以下代码,利用Gatsby的@link指令建立两个JSON类型的关联:

exports.createSchemaCustomization = ({ actions }) => {
  const { createTypes } = actions;
  const typeDefs = `
    # 定义LocationsJson类型,指定posts字段关联到PostsJson列表
    type LocationsJson implements Node {
      id: ID!
      name: String!
      # 通过posts数组中的ID,匹配PostsJson的id字段
      posts: [PostsJson!]! @link(by: "id")
    }

    # 定义PostsJson类型,可选添加反向关联到LocationsJson
    type PostsJson implements Node {
      id: ID!
      title: String!
      content: String!
      # 反向关联:通过当前文章ID匹配LocationsJson的posts数组
      location: LocationsJson @link(by: "posts")
    }
  `;
  createTypes(typeDefs);
};

步骤2:重启Gatsby并测试查询

重启你的Gatsby开发服务器(gatsby develop),然后打开GraphQL Playground(默认是http://localhost:8000/___graphql),测试以下查询:

query GetLocationsWithPosts {
  allLocationsJson {
    nodes {
      id
      name
      # 现在可以直接获取关联的文章对象了
      posts {
        id
        title
        content
      }
    }
  }
}

你会看到每个位置的posts字段不再是单纯的ID数组,而是对应的文章对象列表,完全符合你的需求~

一些注意事项

  • 确保两个JSON文件中的ID是唯一且匹配的,否则关联会失效;
  • 如果你的locations里的posts字段是单个ID(不是数组),只需要把Schema里的[PostsJson!]!改成PostsJson!即可;
  • 反向关联的location字段是可选的,如果你不需要从文章查询所属位置,可以删掉这部分定义。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:57:39